如何使用 PHP 输出压缩的 HTML 代码

对于服务器输出的 HTML 代码,下面的 PHP 函数可以对 HTML 进行压缩:

function aiboshuo_minify_html($html) {
    return preg_replace(
        $search = array(
            '/\>[^\S ]+/s',  // 删除标签后面空格
            '/[^\S ]+\</s',  // 删除标签前面的空格
            '/(\s)+/s'       // 将多个空格合并成一个
        ), 
        array(
            '>',
            '<',
            '\\1'
        ), 
        $html
    );
}

对于 WordPress 博客来说,将上面的函数和下面的代码复制到当前主题的functions.php文件中,就可以实现输出页面 HTML 代码的压缩:

if(!is_admin()){
	add_action("wp_loaded", 'wp_loaded_minify_html');
	function wp_loaded_minify_html(){
		ob_start('aiboshuo_minify_html');
	}
}

原文来自http://blog.wpjam.com/m/wpjam_minify_html/