【问题标题】:Minify HTML output, but preserve certain tags缩小 HTML 输出,但保留某些标签
【发布时间】:2013-02-04 16:56:40
【问题描述】:

我正在开发一个功能,通过去除不必要的空格、换行符和制表符,以及其中的 cmets 来缩小我的页面的 HTML 代码。 但是,我想保留以

开头的标签
 "<!-- google_ad_section... -->"

因为他们告诉 Google 需要强调我页面的哪些部分。

我当前用于修剪代码的代码 sn-p 是这个,在这个很棒的网站的另一个地方找到。我对参数编码的理解与了解第二个参数的第一部分清除了所有 cmets .. 但是如何保留所有包含“google_ad_section”字符串的标签?

function sanitize_output2($buffer){
return preg_replace(
array(
    '/ {2,}/',
    '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
),
array(
    ' ',
    ''
),
$buffer
);
}

【问题讨论】:

  • 通常称为“缩小”而不是“清理”。
  • 感谢提示,我改了标题。

标签: php string escaping


【解决方案1】:

这个解决方案怎么样:

  • 通过DOMDocument 运行您的HTML
  • 使用选项preserveWhiteSpacefalse 删除所有多余的空格
  • 过滤所有与您需要的不同的 cmets

也许它看起来像这样:

$html = '<html>[…]</html>';

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false; 
$doc->loadHtml($html);

$xpath = new DOMXPath($doc);
$comments = $xpath->query('//comment()');
foreach ($comments as $comment) {
    if (!preg_match('/^google_ad_section /', $comment->nodeValue)) {
        $comment->parentNode->removeChild($comment);
    }
}

$html = $doc->saveHTML();

我是用心写的,没有测试它。所以可能不是 100% 准确。

【讨论】:

    【解决方案2】:

    请务必查看 strip_tags() 函数;尤其是第二个参数。

    strip_tags($html_string,$allowable_tags);
    

    http://php.net/manual/en/function.strip-tags.php

    还有 trim() 函数;再次检查第二个参数。

     trim($html_string,$charlist)
    

    http://www.php.net/manual/en/function.trim.php

    您可能还想查看 Apache 的 mod_deflate,它将压缩输出。

    http://httpd.apache.org/docs/2.2/mod/mod_deflate.html

    但这仅适用于 HTML 文件。要压缩 PHP 输出,您需要使用 zlib.output_compression = On 在站点范围内的 php.ini 文件中或在运行时使用

    ini_set("zlib.output_compression", "On");
    

    http://php.net/manual/en/zlib.configuration.php

    【讨论】:

    • 谢谢,但根据文档,我不能将它用于此特定目的,因为标签的格式类似于注释并且还包含空格,这两个都是 strip_tags() 函数“杀死” .
    猜你喜欢
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 2016-07-05
    • 2019-05-15
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多