PHP function to remove whitespace & comments (Minify HTML)


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.

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(

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

    return $buffer;