Saturday, January 10, 2009

Cleaning/Stripping/Removing empty lines using PHP Regex (Regular Expressions)

Removing empty lines from whole chunk of HTML/CSS/Javascript output would do great effects. With the function below which uses preg_replace (Perl-Compatible Regular Expressions - PCRE Regex), you can easily strip off empty lines, which can improve your application's workload and speed.

function removeEmptyLines($s)
{
return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $s);
}


Use the function to clean buffers of HTML, CSS or Javascript before outputting to browsers/clients. It will do a great deal of magic.

3 comments:

Dork said...

Short n sweet!

Like it!

thephpdeveloper said...

thanks Dork!

new2php said...

that is great!, I'm very new to php,

Just wondering how do you use this in a php file where you can open a text file remove empty lines and close the file.

Please help