正则表达式,仅压缩页面的某些部分

时间:2011-03-29 06:17:44

标签: php regex compression

我有一个函数可以在将页面保存到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;

}

2 个答案:

答案 0 :(得分:0)

在解析HTML时,已知正则表达式是邪恶的(请参阅thisthis)。

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

答案 1 :(得分:0)

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