6

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/

4
  • Did you mean: "Should become: line1 \n \n line2"? Commented May 18, 2012 at 15:58
  • Basically if there are more than 2 empty lines between every line, it should be trimmed down to just one. So basically that remaining empty line should be as high as 1 em. Commented May 18, 2012 at 16:01
  • I think you need to define what you mean by 'empty line'. What you describe in the question isn't an empty line. Commented May 18, 2012 at 16:10
  • I just added a quick example at jsfiddle.net/RAqSS Commented May 18, 2012 at 16:24

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This one works precisely! If you don't want empty line, you would use the following code: preg_replace('/\n(\s*\n)+/', "\n", $output);
4

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.

8 Comments

That doesn't work. It somehow removes all content, leaving an empty string.
'\n' is not a single newline.
@KendallFrey - Thanks, originally OP was asking for line\nline2 but it looks like you were interpreting it correctly based on the jsfiddle.
@Sempiterna - I just noticed that I had forgotten the trailing / on the regex, that may have caused the problem. Glad you were able to find a working solution!
By the way, see mine and AshleyS's answers for the correct way to put a newline in string.
|
0

Based on your jsFiddle, try this:

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

2 Comments

Your second code almost works. It replaces all empty lines and replaces them with an empty line between each piece of text. But it also adds an empty line between each piece of text that did not have multiple empty lines.
Can you update your question with a more detailed example of your data and expected results?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.