Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_split: Split string by other strings

I want to split a large string by a series of words.

E.g.

$splitby = array('these','are','the','words','to','split','by');
$text = 'This is the string which needs to be split by the above words.';

Then the results would be:

$text[0]='This is';
$text[1]='string which needs';
$text[2]='be';
$text[3]='above';
$text[4]='.';

How can I do this? Is preg_split the best way, or is there a more efficient method? I'd like it to be as fast as possible, as I'll be splitting hundreds of MB of files.

like image 601
Alasdair Avatar asked Dec 09 '22 04:12

Alasdair


2 Answers

This should be reasonably efficient. However you may want to test with some files and report back on the performance.

$splitby = array('these','are','the','words','to','split','by');
$text = 'This is the string which needs to be split by the above words.';
$pattern = '/\s?'.implode($splitby, '\s?|\s?').'\s?/';
$result = preg_split($pattern, $text, -1, PREG_SPLIT_NO_EMPTY);
  • Regular Expression Demo: http://rubular.com/r/jNUO1KvrXg
  • PHP Code Demo: http://www.ideone.com/ov3Wl
like image 89
mellamokb Avatar answered Dec 30 '22 08:12

mellamokb


preg_split can be used as:

$pieces = preg_split('/'.implode('\s*|\s*',$splitby).'/',$text,-1,PREG_SPLIT_NO_EMPTY);

See it

like image 28
codaddict Avatar answered Dec 30 '22 10:12

codaddict