$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 follow the preg_replace's tutorial, however this code produce
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
Answer: Use the Newline Characters ' \n ' or ' \r\n ' You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.
Yes it does, see the manual: This function returns a string with whitespace stripped from the beginning and end of str .
Whitespaces are generally ignored in PHP syntax, but there are several places where you cannot put them without affecting the sense (and the result).
The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With