PHP explode() white space issue

I’ve got an issue with spacing in strings when I do explode(); I’m sure there is an easy fix for this

The user enters a string into a form like this:
one, two, three, four, five, six
OR like this
one,two,three,four,five,six
sometimes they enter spaces after the commas, sometimes they don’t. that is up to them, but it can screw up my explosion

That string is saved as $keywords. I would like to explode $keywords so I can break it apart.

If I do this:
$exploded = explode(‘,’, $keywords);
then, that will a blank space in front of each keyword

If I do this:
$exploded = explode(', ', $keywords); //with a space after the comma
then, that wont work for people that don’t put spaces between their keywords

Is there a better way to explode? or, if not, is there code that will take off the first character of a string if it is a blank white space?

You can use trim() after an “explosion” to eliminate the white space.

Untested Code:


$arrKeywords = explosion(",", $strKeywords)

foreach($arrKeywords as $index => $word)
   $arrKeywords[$index] = trim($word);


www.php.net is an amazing source for php help.

-Cilverphox

awesome, that worked great. thanks phox!

Nothing wrong with Cilverphox’s answer but you can do it in one line if you like:


$keywordsArray = array_map('trim', explode(',', $keywords));

A better solution I think would be the following


$keywords = "one, two , three      , four";
$keyword_array=explode(",", trim($keywords));

print_r($keyword_array); 

//should just output 
/* 
Array 
( 
    [0] => one 
    [1] => two 
    [2] => three 
    [3] => four 
) 
*/ 

This would avoid using the array map and stripping the white space on each of the exploded elements.

No Trim required…


$s = preg_split( '/[, ]+/', $data, -1, PREG_SPLIT_NO_EMPTY );

But that won’t trim anything inside $keywords. It will only trim the left and the right of the full $keywords string.

You’ll have to use the solution given by cilverphox or markl999 instead.