PHP - remove extra spaces, but not new lines

I was looking for a way to remove extra spaces from a string (i.e. if two or more spaces are next to each other, leave only 1 and delete the rest), I found this to Remove extra spaces from a string , and I wanted to use this solution:

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

but it also removes new lines while I want to keep them. Is there a way to keep newlines when removing extra spaces?

+7
source share
2 answers

http://www.php.net/manual/en/regexp.reference.escape.php defines \h any horizontal whitespace character (since PHP 5.2.4) so you are probably looking

$foo = preg_replace( '/\h+/', ' ', $foo );

example: http://ideone.com/NcOiKW

+19
source

if you want to remove the excess of only spaces (not tabs, newlines, etc.), you can use the HEX code for more specific ones:

  $text = preg_replace('/\x20+/', ' ', $text); 
+4
source

All Articles