user4295236
user4295236

Reputation:

Explode function ignores space character

php:

$str="M. M. Grice and B. H. Alexander and L. Ukestad ";
// I need to explode the string by delimiter "and"
$output=explode("and",$str);

Output:
M. M. Grice
B. H. Alex
er
L. Ukestad

In the name "Alexander" there is a "and" so that too was splitted. So, I changed it to $output=explode(" and ",$str)// as delimiter "and" has space. But it dint work.

where am I doing mistake? I tried $output=explode("\ and\ ",$str). But none of them worked

Expected Output:
M. M. Grice
B. H. Alexander
L. Ukestad

Upvotes: 1

Views: 467

Answers (2)

axiac
axiac

Reputation: 72226

The code provided in the question:

$output=explode(" and ", $str);

is the correct way to get the desired output.

It does not work when the characters around the and in the input string $str are not regular spaces (" " == chr(32)) but tabs ("\t" == chr(9)), newlines ("\n" == chr(10)) or other white space characters.

The string can be split using preg_split():

$output = preg_split('/\sand\s/', $str);

will use and surrounded by any whitespace character as a delimiter.

Another regex that can be used is:

$output = preg_split('/\band\b/', $str);

this will split $str using the word and as delimiter, no matter what characters (non-letter, non-digit, non-underscore) surround it. It will recognize and as a delimiter in the string provided in the question but also in "M. M. Grice and B. H. Alexander (and L. Ukestad)".

An undesired side-effect is that the spaces around and are not part of the delimiter and they will remain in the split fragments. They can be easily removed by trimming the pieces returned by preg_split():

$str = "M. M. Grice and B. H. Alexander (and L. Ukestad)";
$output = array_map('trim', preg_split('/\band\b/', $str));
var_export($output);

will display:

array (
  0 => 'M. M. Grice',
  1 => 'B. H. Alexander (',
  2 => 'L. Ukestad)',
)

Upvotes: 2

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

Try this better by regex: preg_split("/\\sand\\s/i",$str); it explode in case (AND & and) both ..

Upvotes: 1

Related Questions