$string = \"My text has so much whitespace
Plenty of spaces and tabs\";
echo preg_replace(\"/\\s\\s+/\", \" \", $string);
Had the same problem when passing echoed data from PHP to Javascript (formatted as JSON). The string was peppered with useless \r\n and \t characters that are neither required nor displayed on the page.
The solution i ended up using is another way of echoing. That saves a lot of server resources compared to preg_replace (as it is suggested by other people here).
Here the before and after in comparison:
Before:
echo '
Example
Example
';
Output:
After:
echo
'',
'Example',
'Example',
'';
Output:
(Yes, you can concatenate echo not only with dots, but also with comma.)