PHP function to remove whitespace & comments (Minify HTML)

Sitebee

Freelance Technical SEO
Staff member
Use this handy PHP function to remove all whitespace in HTML pages, effectively minifying the HTML page. This will shave off a few kb's on large HTML pages rendered using PHP.

Code:
function sanitize_output($buffer) {

    $search = array(
        '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
        '/[^\S ]+\</s',     // strip whitespaces before tags, except space
        '/(\s)+/s',         // shorten multiple whitespace sequences
        '/<!--(.|\s)*?-->/' // Remove HTML comments
    );

    $replace = array(
        '>',
        '<',
        '\\1',
        ''
    );

    $buffer = preg_replace($search, $replace, $buffer);

    return $buffer;
}

ob_start("sanitize_output");