A Simple Minifier for PHP Sites

Created by josh
April 12, 2016 1:11:15 PM PDT


Minify your HTML in 4 simple regular expressions

For those of you looking to improve your SEO optimization, a key factor in rendering HTML quickly is to ensure your HTML output is minified properly. This means getting your HTML output onto one line and eliminating unnecessary whitespace and comments throughout the HTML itself.

If your site is written in PHP, this is relatively easy. You can write a method that takes the output and echos out some preg_replaced() items to help minify your code.

public static function html($input)
{
    $find_replace = [
        "~\s+~" => " ",
        "~\s{2,}~" => " ",
        "~>\s<~" => "><",
        "~<!--.*?-->~" => null,
    ];

    $find       = array_keys($find_replace);
    $replace    = $find_replace;

    return preg_replace($find, $replace, $input);
}

Since all my output is echoed from a single variable, I only need to apply this once.

    // output page here

    echo \View\Html\Minify::html($my_entire_page);

However, if you've "included" or "required" other content (such as the header, or some HTML pieces) which have already been output by "echo" or simply exist as HTML, you can wrap it in an output buffer:

    // header
    ob_start();
    require('header.php');
    $header = ob_get_clean();

    // body
    $rest_of_page = 'body of page goes here';

    // footer
    ob_start();
    require('footer.php');
    $footer = ob_get_clean();

    // echoing it all out to one line of HTML
    echo \View\Html\Minify::html($header);
    echo \View\Html\Minify::html($rest_of_page);
    echo \View\Html\Minify::html($footer);

    // or, of course.... echo \View\Html\Minify::html($header . $rest_of_page . $footer);