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: Title of string Our objective is to convert this text to: Title of string 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.
|