Skip to content

php - how to explode a string with multiple delimiters without using preg_split

The task is to split a string by a set of delimiters. preg_split could be an option but there is an easier way ;-). Why not combine str_replace and explode? First, we replace all known delimiters with a special (and hopefully unique) string. After that, we have a string with one delimiter, so it became a suitable task for explode. Take a look to the sourcecode below.

<\?php $nl = PHP_EOL; $string = 'Word1, Word2 , Word3 and Word4 or Word5 oder Wort6 / Word 7 Word-8'; $delimiters = array( ', ', ' , ', ' oder ', ' or ', ' / ', ' und ', ' and ' ); $words = array(); $unionPlaceholder = 'ARTODETO_BAZZLINE_NET_UNION_PLACEHOLDER'; $unifiedString = str_replace($delimiters, $unionPlaceholder, $string); $words = explode($unionPlaceholder, $unifiedString); echo 'splitting following string:' . $nl . '"' . $string . '"' . $nl; echo '----' . $nl; foreach ($words as $word) { echo $word . $nl; }
You see, no magic but a possible timesaver. Have fun with it.

howto - regex - apache php

Currently, there is no howto. But by the time of running into and solving problems with regex, a view pages helped my a lot. So here they are. regex php german by phpwcms-howto.de regex howto german by danielfett.de regex howto english by zytrax.com regex in apache mod_rewrite by apache.org regex online tool by gskinner.com regex online test by regexplanet.com