PHP Regex - 删除冗余空格但保留换行符

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!

Remove spaces and tabs

preg_replace("/[ \t]+/", " ", $myval);

Remove only spaces

preg_replace("/[ ]+/", " ", $myval);

Removes 2 ore more spaces:

preg_replace("/[ ]{2,}/", " ", $myval);

This will replace all "spaces" but newline by a space

$str = "a   bc


d e       f";
$str = preg_replace('/[^\S
]+/', ' ', $str);
echo $str,"
";

output:

a bc


d e f

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);