Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we do multiple explode statements on one line in PHP?

Tags:

php

explode

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.

like image 400
Harinder Avatar asked May 14 '12 04:05

Harinder


People also ask

What is the difference between explode () and split () functions?

Both the functions are used to Split a string. However, Split is used to split a string using a regular expression. On the other hand, Explode is used to split a string using another string.

What does explode () do in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

Which function takes a string blast it and breaks it into smaller pieces in PHP?

The str_split() function splits a string into an array.


1 Answers

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 
)
like image 78
Sampson Avatar answered Sep 29 '22 11:09

Sampson