7

Can we do multiple explode() in PHP?

For example, to do this:

foreach(explode(" ",$sms['sms_text']) as $no)
foreach(explode("&",$sms['sms_text']) as $no)
foreach(explode(",",$sms['sms_text']) as $no)

All in one explode like this:

foreach(explode('','&',',',$sms['sms_text']) as $no)

What's the best way to do this? What I want is to split the string on multiple delimiters in one line.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Harinder
  • 1,257
  • 8
  • 27
  • 54

5 Answers5

17

If you're looking to split the string with multiple delimiters, perhaps preg_split would be appropriate.

$parts = preg_split( '/(\s|&|,)/', 'This and&this and,this' );
print_r( $parts );

Which results in:

Array ( 
  [0] => This 
  [1] => and 
  [2] => this 
  [3] => and 
  [4] => this 
)
Sampson
  • 265,109
  • 74
  • 539
  • 565
4

Here is a great solution I found at PHP.net:

<?php

//$delimiters must be an array.

function multiexplode ($delimiters,$string) {

    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);

print_r($exploded);

//And output will be like this:
// Array
// (
//    [0] => here is a sample
//    [1] =>  this text
//    [2] =>  and this will be exploded
//    [3] =>  this also 
//    [4] =>  this one too 
//    [5] => )
// )

?>
ethanpil
  • 2,522
  • 2
  • 24
  • 34
2

you can use this

function multipleExplode($delimiters = array(), $string = ''){

    $mainDelim=$delimiters[count($delimiters)-1]; // dernier

    array_pop($delimiters);

    foreach($delimiters as $delimiter){

        $string= str_replace($delimiter, $mainDelim, $string);

    }

    $result= explode($mainDelim, $string);
    return $result;

} 
JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
Saleeh
  • 392
  • 4
  • 15
0

You could use preg_split() function to stplit a string using a regular expression, like so:

$text = preg_split('/( |,|&)/', $text);
Crozin
  • 43,890
  • 13
  • 88
  • 135
0

I'd go with strtok(), eg

$delimiter = ' &,';
$token = strtok($sms['sms_text'], $delimiter);

while ($token !== false) {
    echo $token . "\n";
    $token = strtok($delimiter);
}
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Of aaaaaaaaaaaall the duplicates for this task, this is the first time that someone actually included an implementation of `strtok()` instead of just plonking a link to the PHP docs. Good on ya. (...but the OP does ask for a one-liner) – mickmackusa Mar 12 '22 at 10:33