Web Hosting Talk







View Full Version : PHP EXPLOSION! (strings)


Goldfiles
10-08-2006, 02:51 AM
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?

Burhan
10-08-2006, 03:19 AM
is there code that will take off the first character of a string if it is a blank white space?

http://php.net/ltrim (removes whitespace on the left of a string)
http://php.net/rtrim (removes whitespace on the right of a string)
http://php.net/trim (removes any leading or trailing whitespace)

Goldfiles
10-08-2006, 03:21 AM
cool, thx!

Renard Fin
10-08-2006, 01:16 PM
or simpler

$string = "one, two, tree, four";

$string = str_replace(' ', '', $string);

$array = explode (',', $string);

et voila ;)

Burhan
10-08-2006, 04:44 PM
There is a bug in your code Renard, in that if the string contains spaces itself, then your code will mangle the string.

Consider:


$string = "one two, three four, five six, seven";
echo str_replace(' ','',$string);