【问题标题】:Regular expression that will only compress certain sections of the page只会压缩页面某些部分的正则表达式
【发布时间】:2011-03-29 06:17:44
【问题描述】:

我有一个函数可以在将页面保存到 HTML 文件以进行缓存之前从我的 php 页面的输出中去除不需要的空格。

但是,在我的页面的某些部分,我在 pre 标记中有源代码,这些空格会影响代码的显示方式。我的正则表达式技巧很糟糕,所以我基本上是在寻找一种解决方案来阻止这个函数与里面的代码混淆:

 <pre></pre>

这是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
           );
      $replace = array(
         '>',
         '<',
         '\\1',
         );
    $buffer = preg_replace($search, $replace, $buffer);
      return $buffer;
   }

感谢您的帮助。

这是我发现的工作:

解决方案:

function stripBufferSkipPreTags($buffer){
$poz_current = 0;
$poz_end = strlen($buffer)-1;
$result = "";

while ($poz_current < $poz_end){
    $t_poz_start = stripos($buffer, "<pre", $poz_current);
    if ($t_poz_start === false){
        $buffer_part_2strip = substr($buffer, $poz_current);
        $temp = stripBuffer($buffer_part_2strip);
        $result .= $temp;
        $poz_current = $poz_end;
    }
    else{
        $buffer_part_2strip = substr($buffer, $poz_current, $t_poz_start-$poz_current);
        $temp = stripBuffer($buffer_part_2strip);
        $result .= $temp;
        $t_poz_end = stripos($buffer, "</pre>", $t_poz_start);
        $temp = substr($buffer, $t_poz_start, $t_poz_end-$t_poz_start);
        $result .= $temp;
        $poz_current = $t_poz_end;
    }
}
return $result;

}

function stripBuffer($buffer){
// change new lines and tabs to single spaces
$buffer = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $buffer);
// multispaces to single...
$buffer = preg_replace(" {2,}", ' ',$buffer);
// remove single spaces between tags
$buffer = str_replace("> <", "><", $buffer);
// remove single spaces around &nbsp;
$buffer = str_replace(" &nbsp;", "&nbsp;", $buffer);
$buffer = str_replace("&nbsp; ", "&nbsp;", $buffer);
return $buffer;

}

【问题讨论】:

  • 你在压缩磁盘空间吗?如果是这样,您是否考虑过使用 gz 压缩? (php.net/gz_deflate)
  • @Adam - 你是对的。这应该是一个答案,而不是评论。另见:stackoverflow.com/questions/3095424/minify-html-php
  • 只是不要这样做。如果您想节省几个字节,请使用 html 压缩器,不要尝试使用一些 hack-job 正则表达式来滚动您自己的;你会创造比你解决的更多的问题。
  • 请注意,任何元素都可以通过添加whitespace:pre CSS 声明来使用预格式化声明。 &lt;code&gt; 通常是另一个预先格式化的元素。如果您不在超高流量场景中,那么 HTML 缩小的整个想法就毫无意义。如果您想节省带宽,请发送压缩后的内容。

标签: php regex compression


【解决方案1】:

在解析 HTML 时,正则表达式被认为是邪恶的(参见 thisthis)。

也就是说,尝试以另一种方式做您需要的事情,例如使用 DOM 解析器并自定义其 HTML 输出函数。

【讨论】:

    【解决方案2】:

    如果您要压缩磁盘空间,则应考虑使用 gz 压缩。 (php.net/gz_deflate)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 2018-06-04
      • 2013-02-18
      • 1970-01-01
      相关资源
      最近更新 更多