I don't think using prere regex is necessary ... if it really separates the words you need.
You could do something similar, and breakpoints will see if it will be faster / better ...
$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);
The only difference from your conclusion is the last word, because "words".! = "Word", and this is not a divided word.
source share