minifying final html output using regex with codeigniter

Posted by Aman on Stack Overflow See other posts from Stack Overflow or by Aman
Published on 2011-03-15T13:22:23Z Indexed on 2011/03/18 0:10 UTC
Read the original article Hit count: 221

Filed under:
|
|
|

Google pages suggest you to minify html i.e. remove all the un-necessary spaces. Codeigniter does have feature of giziping output or it can be done via .htaccess. But still I also would like to remove un-necessary spaces from final html output as well.

I played a bit with this peace of code to do it, and it seem to work. This does indeed result in html that is without excess spaces and removes other tab formatting.

class Welcome extends CI_Controller 
{
    function _output()
    {
        echo preg_replace('!\s+!', ' ', $output);
    }

    function index(){
    ...
    }
}

Now the problem with this is there may be tag like <pre>,<textarea>, etc.. which may have space in it and regx should remove them. So, how do I remove excess space from final html, without effecting spaces or formatting for these certain tags using regx?

Thanks to @Alan Moore got the answer, this worked for me

echo preg_replace('#(?ix)(?>[^\S ]\s*|\s{2,})(?=(?:(?:[^<]++|<(?!/?(?:textarea|pre)\b))*+)(?:<(?>textarea|pre)\b|\z))#', ' ', $output);

@ridgerunner here did very good job of analyzing this regx, ended up using his solution. Cheers to ridgerunner.

© Stack Overflow or respective owner

Related posts about php

Related posts about regex