Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Remove excess Whitespace but not new lines

i was looking for a way to remove excess whitespaces from within a string (that is, if 2 or more spaces are next each other, leave only 1 and remove the others), i found this Remove excess whitespace from within a string and i wanted to use this solution:

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

but this removes new lines aswell, while i want to keep them. Is there any way to keep newlines while removing excess whitespace?

like image 220
valepu Avatar asked May 24 '13 00:05

valepu


2 Answers

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

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

example: http://ideone.com/NcOiKW

like image 108
test30 Avatar answered Oct 15 '22 14:10

test30


if you want to remove excess of only-spaces (not tabs, new-lines, etc) you could use HEX code to be more specific:

    $text = preg_replace('/\x20+/', ' ', $text);
like image 27
JuanLigas Avatar answered Oct 15 '22 12:10

JuanLigas