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