goldfiles — 2006-10-08T02:52:27-04:00 — #1
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
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?
cilverphox — 2006-10-08T03:01:45-04:00 — #2
You can use trim() after an "explosion" to eliminate the white space.
$arrKeywords = explosion(",", $strKeywords)
foreach($arrKeywords as $index => $word)
$arrKeywords[$index] = trim($word);
www.php.net is an amazing source for php help.
goldfiles — 2006-10-08T03:05:18-04:00 — #3
awesome, that worked great. thanks phox!
markl999 — 2006-10-08T04:34:15-04:00 — #4
Nothing wrong with Cilverphox's answer but you can do it in one line if you like:
$keywordsArray = array_map('trim', explode(',', $keywords));
bravoclicks — 2010-08-17T15:06:35-04:00 — #5
A better solution I think would be the following
$keywords = "one, two , three , four";
//should just output
 => one
 => two
 => three
 => four
This would avoid using the array map and stripping the white space on each of the exploded elements.
logic_earth — 2010-08-17T21:25:15-04:00 — #6
No Trim required...
$s = preg_split( '/[, ]+/', $data, -1, PREG_SPLIT_NO_EMPTY );
paul_wilkins — 2010-08-17T21:27:08-04:00 — #7
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.