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.
Comments
Display comments as Linear | Threaded