Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace excess whitespaces and line-breaks with PHP?

$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

like image 436
Teiv Avatar asked Jun 18 '11 06:06

Teiv


People also ask

How can I break line in PHP?

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.

Does PHP trim Remove newline?

Yes it does, see the manual: This function returns a string with whitespace stripped from the beginning and end of str .

Does PHP care about whitespace?

Whitespaces are generally ignored in PHP syntax, but there are several places where you cannot put them without affecting the sense (and the result).

How do I strip whitespace in PHP?

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.


1 Answers

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.

like image 72
Francois Deschenes Avatar answered Oct 14 '22 05:10

Francois Deschenes