Using preg_split() to explode() by multiple delimiters in PHP

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.

$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 returned 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:

$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:

<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.

$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

Leave a Reply

Your email address will not be published. Required fields are marked *