Just a quick note here. To explode() a string using multiple delimiters in PHP you will have to make use of the regular expressions. Use pipe character to separate your delimiters.
1 |
$chunks = preg_split('/(de1|del2|del3)/',$string,-1, PREG_SPLIT_NO_EMPTY); |
There are also various flags you can use as optional:
- PREG_SPLIT_NO_EMPTY – To return only non-empty pieces.
- PREG_SPLIT_DELIM_CAPTURE – To capture and return the parenthesized expression in the delimiter.
- PREG_SPLIT_OFFSET_CAPTURE – To return the appendant string offset for every occurring match.
Here is a simple example of usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$string = ' <ul> <li>Name: John</li> <li>Surname- Doe</li> <li>Phone* 555 0456789</li> <li>Zip code= ZP5689</li> </ul> '; $chunks = preg_split('/(:|-|\*|=)/', $string,-1, PREG_SPLIT_NO_EMPTY); // This is just a simple way to debug stuff ;-) echo '<pre>'; print_r($chunks); echo '</pre>'; |
…and this is the output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<pre>Array ( [0] => <ul> <li>Name [1] => John</li> <li>Surname [2] => Doe</li> <li>Phone [3] => 555 0456789</li> <li>Address [4] => Str Preg Split example</li> <li>Zip code [5] => ZP5689</li> </ul> ) </pre> |
Now let’s put everything back together in a nice form.
1 2 3 4 5 |
$nweString = $chunks[0]; for($i=1; $i<count($chunks); $i++) { $nweString .= ':'.$chunks[$i]; } echo $nweString; |
Enjoy this simple, yet powerful way to split a string by multiple delimiters in PHP. You can further read about the preg_split() function on the PHP documentation site here http://php.net/manual/en/function.preg-split.php