Sriram Ranganathan Sriram Ranganathan - 1 month ago 6
PHP Question

How to correctly replace multiple white spaces with a single white space in PHP?

I was scouring through SO answers and found that the solution that most gave for replacing multiple spaces is:

$new_str = preg_replace("/\s+/", " ", $str);


But in many cases the white space characters include UTF characters that include line feed, form feed, carriage return, non-breaking space, etc. This wiki describes that UTF defines twenty-five characters defined as whitespace.

So how do we replace all these characters as well using regular expressions?

Answer

When passing u modifier, \s becomes Unicode-aware. So, a simple solution is to use

$new_str = preg_replace("/\s+/u", " ", $str);
                             ^^

See the PHP online demo.