Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty lines from string, but allow one empty between every line

Tags:

regex

php

I would like to remove excessive empty lines from a string, but allow one empty line between every line. Like:

line1





line2

Should become:

line1

line2

I did find 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 every line.

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

like image 925
Sempiterna Avatar asked May 18 '12 15:05

Sempiterna


People also ask

How do you remove blank lines in a text?

Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text.

How do you remove blank lines from text in Python?

strip() != "" to remove any empty lines from lines . Declare an empty string and use a for-loop to iterate over the previous result. At each iteration, use the syntax str1 += str2 + "/n" to add the current element in the list str2 and a newline to the empty string str1 .


2 Answers

Try replacing:

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

with:

\n\n

Like this:

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

If you don't want an empty line, you would change the {2,} to a + and use a single \n. It would actually work with a + instead of {2,}. The {2,} is an optimization.

like image 100
Kendall Frey Avatar answered Oct 26 '22 18:10

Kendall Frey


Try the following:

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

This will replace a newline followed by any number of blank lines with a single newline.

like image 24
Andrew Clark Avatar answered Oct 26 '22 18:10

Andrew Clark