real way to get rid of white space

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

real way to get rid of white space

Post by shiznatix »

is there a real good way to get rid of extra whitespace within a string?
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post 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
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post by malcolmboston »

loop through each letter and do an if($letter= " "); remove clause
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

how do you loop through each letter? and also that would destroy the valid 1 space characters. how should i aviod that?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

exactally what i wanted, many thanks
Post Reply