Remove the empty lines from the line, but allow the empty between each line

I would like to remove the extra empty lines from the line, but allow one empty line between each line. How:

line1 line2 

It should become:

 line1 line2 

I found the following regex (forgot where I found it):

 preg_replace('/^\n+|^[\t\s]*\n+/m','',$message); 

This works, but removes all empty lines without leaving an empty line between each line.

Edit: I just created a quick example at http://jsfiddle.net/RAqSS/

+6
source share
3 answers

Try replacing:

 \n(\s*\n){2,} 

from:

 \n\n 

Like this:

 preg_replace('/\n(\s*\n){2,}/', "\n\n", $message); // Quotes are important here. 

If you do not want an empty string, you must change {2,} to + and use one \n . It will work with + instead of {2,} . {2,} - optimization.

+6
source

Try the following:

 preg_replace('/\n(\s*\n)+/', "\n\n", $message); 

This will replace the new line, followed by any number of empty lines with one new line.

+4
source

Based on your jsFiddle, try the following:

 $result = preg_replace('/\n(\n*\s)+/', "\n\n", $message); 
0
source

Source: https://habr.com/ru/post/916106/


All Articles