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.

Trackbacks

Keine Trackbacks

Kommentare

Ansicht der Kommentare: Linear | Verschachtelt

Noch keine Kommentare

Kommentar schreiben

Die angegebene E-Mail-Adresse wird nicht dargestellt, sondern nur für eventuelle Benachrichtigungen verwendet.
Um einen Kommentar hinterlassen zu können, erhalten Sie nach dem Kommentieren eine E-Mail mit Aktivierungslink an ihre angegebene Adresse.

Um maschinelle und automatische Übertragung von Spamkommentaren zu verhindern, bitte die Zeichenfolge im dargestellten Bild in der Eingabemaske eintragen. Nur wenn die Zeichenfolge richtig eingegeben wurde, kann der Kommentar angenommen werden. Bitte beachten Sie, dass Ihr Browser Cookies unterstützen muss, um dieses Verfahren anzuwenden.
CAPTCHA

Markdown-Formatierung erlaubt
Formular-Optionen