Today i was trying to write a regular expression to remove blank lines using the PHP method preg_replace.
After googling it i found this solution being posted online.

PHP: $s = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/","",$s);
Perl: $s =~ s/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]//g;

Input:

-----------------------

hello

-----------------------

Output:

-----------------------
hello-----------------------

Not very nice. Seems that this expression removes newline characters from cases like “string\n\n”.

What it should look like.

-----------------------
hello
-----------------------

My solution:

PHP: $s = preg_replace("/^\n+|^[\t\s]*\n+/m", "", $s);
Perl: $s =~ s/^\n+|^[\t\s]*\n+//mg; #we need to use the g modifier to replace all occurrences preg_replace does this by default.

Output:

-----------------------
hello
-----------------------

Much better. :D