PHP Echo Tutorials

Remove multiple empty lines and replace by a single line

Written by phpecho.com   

In this tutorial, we show you a non-regex method to replace multiple empty lines with a single line break. The problem is described below:
Suppose you have a string like

Title of string

The actual text starts here. Note this could consist of multiple paragraphs. Paragraphs are again separated by line breaks which could be one or more.


For example this second paragraph begins after three line breaks.
While the third paragraph is after a single line break!

Our objective is to convert this text to:

Title of string
The actual text starts here. Note this could consist of multiple paragraphs. Paragraphs are again separated by line breaks which could be one or more.
For example this second paragraph begins after three line breaks.
While the third paragraph is after a single line break!

It appears that this can be easily achieved using the string replace function where by all the line break characters (“\n”) can be replaced by an empty character. But this will not solve our purpose as we want to replace empty lines only in those cases where more than one empty line is present together.

The solution can be easily achieved using various regex expressions but this tutorial will show a non-regex solution using basic PHP functions and a simple logic.

We will browse through the string character by character and check if consecutive characters are new line characters. If they are then the second one is skipped. This way, we are left only with a single new line character.

The code for this example is shown below:

  for($i = 0; $i < strlen($s); $i++)
   {
      $newstr = $newstr . substr($s, $i,  1);
      if(substr($s, $i, 1) == '\n')
           while(substr($s, $i + 1, 1) ==  '\n')
                $i++;
 }

The $newstr above will contain the string expected while $s is the input string.

One common use of this type of logic is when the input is given by the user and you are not sure about how the new lines characters appear in them.