Sunday, August 2, 2009

What is the best way to remove spaces from a string in PHP?

I want to keep single spaces, but remove any instances of 2 or more spaces in a row.





I did a lot of searching and I found two examples, but I don't know what the difference is between them and which is better to use:





$string = preg_replace(‘/ss+/’, ‘ ‘, $string);





or





$string = preg_replace('/\s\s+/', ' ', $string);





Thanks!

What is the best way to remove spaces from a string in PHP?
This is really about how to build a proper regexp:





\s means a whitespace character


s means the letter s


+ means match one or more times





so to replace all instances of multiple spaces with a single space, use just /\s+/ and it will do what you want (ok, and replace single instances as well, but it won't hurt).
Reply:preg_replace is a complex function that involves a lot of "replacement rules". To be avoided when you can!


Instead, use just:


$newstr = str_replace ( space, nothing, string );


space : dble quote, space, dble quote


nothing: dble quote, dble quote.


string: $string or dble quote abcd efg h i dble quote


See www.php.net, str_replace function


No comments:

Post a Comment