PHP a few new lines

I'm a little stuck. How to delete multiple lines of a new line with one new line. Between themselves there can be anything up to 20 new lines. for example

James said hi \ n \ n \ n \ n Test \ n Test two \ n \ n

The result is:

James said hi \ n Test \ n Test two \ n

+6
php regex newline
source share
4 answers

Try the following:

$str = "Hello\n\n\n\n\nWorld\n\n\nHow\nAre\n\nYou?"; $str = preg_replace("/\n+/", "\n", $str); print($str); 
+10
source share

Improving Marc B answer:

 $fixed_text = preg_replace("\n(\s*\n)+", "\n", $text_to_fix); 

Which should match the start new line, then at least one of the group of any number of spaces followed by a new line, and replace it with one new line.

+4
source share
 $fixed_text = preg_replace("\n+", "\n", $text_to_fix); 

This should do this, assuming that the consecutive lines of the new line are really consecutive and do not have spaces (tabs, spaces, carriage returns, etc.) between them.

+1
source share
 $str = 'James said hello\n\n\n\n Test\n Test two\n\n'; echo preg_replace('{(\\\n)\1+}','$1',$str); 
0
source share

All Articles