1

我想用一个字符数组分割一个字符串,我该怎么做?我注意到preg_split接受字符串输入而不是数组。

例如,这是我的数组:

$splitting_strings = array(".", ";", "-", "and", "for");

$text = "What a great day, and I love it. Who knows; maybe I will go.";

$result = array (
0 => "What a great day",
1 => "I love it",
2 =>  "Who knows",
3 => "maybe I will go");
4

1 回答 1

2

您可以通过preg_split()以下内容:

$regex = '/(' . implode('|', $splitting_strings) . ')/';

您将需要转义任何特殊的正则表达式字符,例如.. 所以你应该最终得到这样的东西:

// run through each element in the array escaping any
// special regex chars
$splitting_strings = array_map(function($string) {
                                   return preg_quote($string);
                               }, $splitting_strings);

$regex = '/(' . implode('|', $splitting_strings) . ')/';
$final_array = preg_split($regex, $splitting_strings);

$final_array毕竟这一切的输出是:

array(5) {
  [0]=>
  string(18) "What a great day, "
  [1]=>
  string(10) " I love it"
  [2]=>
  string(10) " Who knows"
  [3]=>
  string(16) " maybe I will go"
  [4]=>
  string(0) ""
}
于 2012-05-21T09:56:32.627 回答