Page 1 of 1

real way to get rid of white space

Posted: Mon May 23, 2005 6:57 am
by shiznatix
is there a real good way to get rid of extra whitespace within a string?

Posted: Mon May 23, 2005 6:59 am
by JayBird

Posted: Mon May 23, 2005 7:03 am
by shiznatix
trim only works on the ends of a string but if my string is "bbbb (lots of whitespace) bbbb" then it wouldnt work on getting rid of the white space in the middle of the string.
This function returns a string with whitespace stripped from the beginning and end of str
i need a way to do it in the middle of the string but i have no idea exactly how much whitespace there is so str_replace really wouldnt be too efficient

Posted: Mon May 23, 2005 7:04 am
by malcolmboston
loop through each letter and do an if($letter= " "); remove clause

Posted: Mon May 23, 2005 7:06 am
by shiznatix
how do you loop through each letter? and also that would destroy the valid 1 space characters. how should i aviod that?

Posted: Mon May 23, 2005 7:10 am
by Chris Corbyn
Pimptastic wrote:http://uk.php.net/trim

?????
Well the problem with trim is that it only trims whitespace from the start and end of the entire string. It wont trim stuff in the middle.

I don't think there's a function to do it but if you want ALL whitespace (newlines, tabs, spaces etc) removing this does it.

Code: Select all

$string = <<<EOD

 La la la la

     dumty dumty dum

I have many spaces in me! Tidy me up a bit 
EOD;

$clean_string = preg_replace('/\s+/', '', $string); //Just make the second parameter a single space to turn excess whitespace into a single space

Posted: Mon May 23, 2005 7:13 am
by shiznatix
exactally what i wanted, many thanks