我认为没有必要使用 pcre 正则表达式......如果它真的是你需要的单词。
你可以做这样的事情并进行基准测试,看看它是否更快/更好......
$splitby = array('these','are','the','words','to','split','by');
$text = 'This is the string which needs to be split by the above words.';
$split = explode(' ', $text);
$result = array();
$temp = array();
foreach ($split as $s) {
if (in_array($s, $splitby)) {
if (sizeof($temp) > 0) {
$result[] = implode(' ', $temp);
$temp = array();
}
} else {
$temp[] = $s;
}
}
if (sizeof($temp) > 0) {
$result[] = implode(' ', $temp);
}
var_dump($result);
/* output
array(4) {
[0]=>
string(7) "This is"
[1]=>
string(18) "string which needs"
[2]=>
string(2) "be"
[3]=>
string(5) "above words."
}
与您的输出的唯一区别是最后一个单词,因为“单词”。!= "word" 并且它不是一个拆分词。