Can we make multiple break statements on the same line in PHP?

Is it possible to do multiple explode () in PHP?

For example, for 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 is the best way to do this? I want to split a string into multiple delimiters on the same line.

+6
source share
5 answers

If you want to split a line with multiple delimiters, perhaps preg_split .

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

Result:

 Array ( [0] => This [1] => and [2] => this [3] => and [4] => this ) 
+15
source

Here is a great solution I found on 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] => ) // ) ?> 
+4
source

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; } 
+2
source

You can use the preg_split() function to format the string using a regular expression, for example:

 $text = preg_split('/( |,|&)/', $text); 
0
source

I would go with strtok() for example

 $delimiter = ' &,'; $token = strtok($sms['sms_text'], $delimiter); while ($token !== false) { echo $token . "\n"; $token = strtok($delimiter); } 
0
source

Source: https://habr.com/ru/post/915632/


All Articles