Jul
18
2011

Exploding a String using Multiple Delimiters Using PHP

Updated February 12th, 2013 to reflect Dave’s comment function below- A++ for simplicity!

function explodeX( $delimiters, $string )
{
    return explode( chr( 1 ), str_replace( $delimiters, chr( 1 ), $string ) );
}

$list = 'Thing 1&Thing 2,Thing 3|Thing 4';

$exploded = explodeX( array('&', ',', '|' ), $list );

echo '<pre>';
print_r($exploded);
echo '</pre>';

Earlier today, I was looking for a simple function to explode text that was contained in string format to be output in array form, however I prefer to avoid Regex whenever possible.  Problem?

Not at all thanks to someone named TcM who was nice enough to post this handy code snippet:


function explodeX($delimiters,$string)

{

$return_array = Array($string); // The array to return

$d_count = 0;

while (isset($delimiters[$d_count])) // Loop to loop through all delimiters

{

$new_return_array = Array();

foreach($return_array as $el_to_split) // Explode all returned elements by the next delimiter

{

$put_in_new_return_array = explode($delimiters[$d_count],$el_to_split);

foreach($put_in_new_return_array as $substr) // Put all the exploded elements in array to return

{

$new_return_array[] = $substr;

}

}

$return_array = $new_return_array; // Replace the previous return array by the next version

$d_count++;

}

return $return_array; // Return the exploded elements

}

And to use the function, we are able to either simply output the newly created array using this code…

Or, we can utilize a simple foreach (which was my usage), and output into a handy multiple line output such as…


$input = "Author 1., Author 2 & Author 3 And Author 4, Author 5"; //The string to be split

$output = explodeX(Array(".,",",","&","And"), $input); //Calling the function using the split parameters

foreach ($output as $o)

{

echo $o . "
";

}

Which outputs:

Author 1
Author 2
Author 3
Author 4
Author 5

Source: http://www.webmastertalkforums.com/php-functions/17184-php-explode-string-multiple-delimiters.html

3 Comments + Add Comment

  • function explodeX($delimiters,$string) {
    return explode(chr(1),str_replace($delimiters,chr(1),$string));
    }

    • Now THAT is beautiful. I’ll be amending my post to reflect that short and sweet masterpiece!

  • superb…awesome…:)

Leave a comment