php:如何用字符数组拆分字符串?

时间:2012-05-21 09:54:27

标签: php string split explode preg-split

我想用字符数组分割字符串,我该怎么做?我注意到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");

1 个答案:

答案 0 :(得分: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) ""
}