14

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?

Community
  • 1
  • 1
valepu
  • 3,136
  • 7
  • 36
  • 67

3 Answers3

30

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+/u', ' ', $foo );

or you can explicitly list all characters you want to affect

$foo = preg_replace( '/\t +/', ' ', $foo );
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
test30
  • 3,496
  • 34
  • 26
  • 2
    I assume it's wrong because for me it removed all whitespace :) – Timo Huovinen Aug 14 '15 at 11:54
  • 2
    For preserving newlines you can do a workaround, like splitting all string by newline into array, cleaning each part and imploding again by newline – Tebe Oct 10 '18 at 13:32
6

If some of your symbols were converted to � after preg_replace (for example, Cyrillic capital letter R / Р), use mb_ereg_replace instead of preg_replace:

$value = mb_ereg_replace('/\h+/', ' ', $value);
Stardisk
  • 61
  • 1
  • 2
5

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('/ +/', ' ', $text);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
JuanLigas
  • 59
  • 1
  • 2