我想用字符数组拆分字符串,我该怎么做?我注意到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");
您可以传递以下内容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) ""
}