How do I remove blank lines from text in PHP?

Viewed 94148

I need to remove blank lines (with whitespace or absolutely blank) in PHP. I use this regular expression, but it does not work:

$str = ereg_replace('^[ \t]*$\r?\n', '', $str);
$str = preg_replace('^[ \t]*$\r?\n', '', $str);

I want a result of:

blahblah

blahblah

   adsa 


sad asdasd

will:

blahblah
blahblah
   adsa 
sad asdasd
14 Answers
// New line is required to split non-blank lines
preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);

The above regular expression says:

/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/
    1st Capturing group (^[\r\n]*|[\r\n]+)
        1st Alternative: ^[\r\n]*
        ^ assert position at start of the string
            [\r\n]* match a single character present in the list below
                Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
                \r matches a carriage return (ASCII 13)
                \n matches a fine-feed (newline) character (ASCII 10)
        2nd Alternative: [\r\n]+
            [\r\n]+ match a single character present in the list below
            Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
            \r matches a carriage return (ASCII 13)
            \n matches a fine-feed (newline) character (ASCII 10)
    [\s\t]* match a single character present in the list below
        Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
        \s match any white space character [\r\n\t\f ]
        \tTab (ASCII 9)
    [\r\n]+ match a single character present in the list below
        Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
        \r matches a carriage return (ASCII 13)
        \n matches a fine-feed (newline) character (ASCII 10)

Your ereg-replace() solution is wrong because the ereg/eregi methods are deprecated. Your preg_replace() won't even compile, but if you add delimiters and set multiline mode, it will work fine:

$str = preg_replace('/^[ \t]*[\r\n]+/m', '', $str);

The m modifier allows ^ to match the beginning of a logical line rather than just the beginning of the whole string. The start-of-line anchor is necessary because without it the regex would match the newline at the end of every line, not just the blank ones. You don't need the end-of-line anchor ($) because you're actively matching the newline characters, but it doesn't hurt.

The accepted answer gets the job done, but it's more complicated than it needs to be. The regex has to match either the beginning of the string (^[\r\n]*, multiline mode not set) or at least one newline ([\r\n]+), followed by at least one newline ([\r\n]+). So, in the special case of a string that starts with one or more blank lines, they'll be replaced with one blank line. I'm pretty sure that's not the desired outcome.

But most of the time it replaces two or more consecutive newlines, along with any horizontal whitespace (spaces or tabs) that lies between them, with one linefeed. That's the intent, anyway. The author seems to expect \s to match just the space character (\x20), when in fact it matches any whitespace character. That's a very common mistake. The actual list varies from one regex flavor to the next, but at minimum you can expect \s to match whatever [ \t\f\r\n] matches.

Actually, in PHP you have a better option:

$str = preg_replace('/^\h*\v+/m', '', $str);

\h matches any horizontal whitespace character, and \v matches vertical whitespace.

The comment from Bythos from Jamie's link above worked for me:

/^\n+|^[\t\s]*\n+/m

I didn't want to strip all of the new lines, just the empty/whitespace ones. This does the trick!

There is no need to overcomplicate things. This can be achieved with a simple short regular expression:

$text = preg_replace("/(\R){2,}/", "$1", $text);

The (\R) matches all newlines.
The {2,} matches two or more occurrences.
The $1 Uses the first backreference (platform specific EOL) as the replacement.

This has been already answered long time ago but can greatly benefit for preg_replace and a much simplified pattern:

$result = preg_replace('/\s*($|\n)/', '\1', $subject);

Pattern: Remove all white-space before a new-line -or- at the end of the string.

Longest match wins:

  • As the white-space \s has a greedy quantifier * and contains \n consecutive empty lines are matched.

  • As \s contains \r as well, \r\n new-line sequences are supported, however single \r (without \n) are not.

  • And when $ matches the end of the buffer the backreference \1 is empty allowing to handle trailing whitespace at the very end, too.

If leading (empty) lines need to be removed as well, they have to match while not capturing, too (this was not directly asked for but could be appropriate):

$result = preg_replace('/^(?:\s*\n)+|\s*($|\n)/', '\1', $subject);
#                        '----------'

Pattern: Also remove all leading white-space (first line(s) are empty).

And if the new-line at the end of the buffer should be normalized differently (always a newline at the end instead of never), it needs to be added: . "\n".

This variant is portable to \r\n, \r and \n new-line sequences ((?>\r\n|\r|\n)) or \R:

$result = preg_replace('/^(?> |\t|\r\n|\r|\n)+|(?> |\t|\r\n|\r|\n)*($|(?>\r\n|\r|\n))/', '\1', $subject);
# or:
$result = preg_replace('/^(?:\s*\R)+|\s*($|\R)/', '\1', $subject);

Pattern: Support all new-line sequences.

This is with the downside that the new-lines can not be normalized (e.g. any of the three to \n).

Therefore, it can make sense to normalize new-lines before removing:

$result = preg_replace(['/(?>\r\n|\n|\r)/', '/\s*($|\n)/'], ["\n", '\1'], $subject);
# or:
$result = preg_replace(['/\R/u', '/\s*($|\n)/'], ["\n", '\1'], $subject);

It ships with the opportunity to do some normalization apart from the line handling.

For example removal of the trailing white-space and fixing the missing new-line at the end of file.

Then doing more advanced line normalization, for example zero empty lines at the beginning and end; otherwise not more than two consecutive empty lines:

$result = preg_replace(
    ['/[ \t]*($|\R)/u', '/^\n*|(\n)\n*$|(\n{3})\n+/'], 
    ["\n"             , '\1\2'                      ], 
    $subject
);

The secondary pattern benefits from the first patterns replacements already.

The power with preg_replace relies here in choosing the backreference(s) to replace with wisely.

Also using multiple patterns can greatly simplify things and keep the process maintainable.

Use this:

$str = preg_replace('/^\s+\r?\n$/D', '', $str);

Try this one:

$str = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\r\n", $str);

If you output this to a text file, it will give the same output in the simple Notepad, WordPad and also in text editors, for example Notepad++.

    <?php

    function del_blanklines_in_array_q($ar){
        $strip = array();
        foreach($ar as $k => $v){
            $ll = strlen($v);
            while($ll--){
                if(ord($v[$ll]) > 32){  //hex /0x20 int 32 ascii SPACE
                    $strip[] = $v; break; 
                }
            }
        }
        return $strip;
    }

    function del_blanklines_in_file_q($in, $out){
        // in filename, out filename
        $strip = del_blanklines_in_array_q(file($in));
        file_put_contents($out, $strip );
    }
$file = "file_name.txt";
$file_data = file_get_contents($file);
$file_data_after_remove_blank_line = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $file_data );
file_put_contents($file,$file_data_after_remove_blank_line);

nl2br(preg_replace('/^\v+/m', '', $r_msg))

Related