function compressHtml($string) { $matches = array(); preg_match_all('/(<(?:pre|code)>.+?<\/(?:pre|code)>)+/is', $string, $matches); foreach ((array)$matches[1] as $k => $v) { $string = str_replace($v, "#{$k}#", $string); } $string = str_replace("\r\n", '', $string); //清除换行符 $string = str_replace("\n", '', $string); //清除换行符 $string = str_replace("\t", '', $string); //清除制表符 $pattern = array ("/> *([^ ]*) *",>/", "/\" /", "/ \"/", "'/\*[^*]*\*/'"); $replace = array (">\\1<", " ", "", "\"", "\"", ""); $string = preg_replace($pattern, $replace, $string); foreach ((array)$matches[1] as $k => $v) { $string = str_replace("#{$k}#", $v, $string); } return $string;} 思路就是提前替换出 pre, code 的块内容.在处理完之后, 再替换回来. ps . 其实那个压缩函数没多大用途. nginx 直接开 gzip 压缩就好了. 效率和性能比用php做要高.