如何缩小HTML代码?

daG*_*vis 8 html min minify html-parsing htmlpurifier

我的想法是以某种方式缩小服务器端的HTML代码,因此客户端接收的字节数更少.

"缩小"是什么意思?

没有拉链.更像是,例如,jQuery创建者使用.min .js版本.换句话说,我需要删除不必要的空格和换行符,但我不能删除那么多的HTML更改表示(例如删除段落中实际单词之间的空格).

有没有可以做到的工具?我知道有HtmlPurifier.它能够做到吗?还有其他选择吗?

PS请不要提供正则表达式.我知道只有Chuck Norris可以用它们解析HTML.=]

Sav*_*ova 10

有点晚但仍然......通过使用output_buffering它就是这么简单:

function compress($string)
{
    // Remove html comments
    $string = preg_replace('/<!--.*-->/', '', $string);

    // Merge multiple spaces into one space
    $string = preg_replace('/\s+/', ' ', $string);   

    // Remove space between tags. Skip the following if
    // you want as it will also remove the space 
    // between <span>Hello</span> <span>World</span>.
    return preg_replace('/>\s+</', '><', $string);      
}

ob_start('compress');

// Here goes your html.    

ob_end_flush();
Run Code Online (Sandbox Code Playgroud)

  • 您可能不希望删除标签中的空格,如pre,code等. (5认同)

Del*_*ani 3

您可以将 HTML 代码解析为 DOM 树(应在节点中保留内容空白),然后将其序列化回 HTML,而不需要任何美化空格。