Reputation: 16536
I'm looking for a regular expression that removes redundant (two or more) spaces but keeps line breaks.
Any idea how that would work?
Thanks in Advance!
Upvotes: 2
Views: 3399
Reputation: 626932
To replace all horizontal whitespace symbols with a single space in a string, you can use
preg_replace('/\h+/', ' ', $str);
where \h
is a PCRE-specific shorthand character class matching all characters that \p{Zs}
matches plus U+0009
(a horizontal tab).
The quantifier +
after \h
enables matching one or more horizontal whitespace symbols. To only match two or more occurrences, use a limiting quantifier:
preg_replace('/\h{2,}/', ' ', $str);
Upvotes: 0
Reputation: 91428
This will replace all "spaces" but newline by a space
$str = "a bc
d e f";
$str = preg_replace('/[^\S\n]+/', ' ', $str);
echo $str,"\n";
output:
a bc
d e f
Upvotes: 2
Reputation: 7219
Remove spaces and tabs
preg_replace("/[ \t]+/", " ", $myval);
Remove only spaces
preg_replace("/[ ]+/", " ", $myval);
Upvotes: 8