3v4l.org

run code in 300+ PHP versions simultaneously
<?php $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);

preferences:
41.44 ms | 402 KiB | 5 Q