Replace tabs and spaces with a single space as well as carriage returns and newlines with a single newline

php, preg-replace, regex, whitespace

Solution

First, I'd like to point out that new lines can be either \r, \n, or \r\n depending on the operating system.

My solution:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/[\r\n]+/', "\n", $string));

Which could be separated into 2 lines if necessary:

$string = preg_replace('/[\r\n]+/', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

Update:

An even better solutions would be this one:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/\s*$^\s*/m', "\n", $string));

Or:

$string = preg_replace('/\s*$^\s*/m', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

I've changed the regular expression that makes multiple lines breaks into a single better. It uses the "m" modifier (which makes ^ and $ match the start and end of new lines) and removes any \s (space, tab, new line, line break) characters that are a the end of a string and the beginning of the next. This solve the problem of empty lines that have nothing but spaces. With my previous example, if a line was filled with spaces, it would have skipped an extra line.

Problem

``` $string = "My text has so much whitespace Plenty of spaces and tabs"; echo preg_replace("/\s\s+/", " ", $string); ``` I read the PHP's documentation and followed the `preg_replace()` tutorial, however this code produces: ``` My text has so much whitespace Plenty of spaces and tabs ``` How can I turn it into : ``` My text has so much whitespace Plenty of spaces and tabs ```

Original source

Related problems