我正在使用一种飞速压缩HTML的方法。以下是功能
function compress_page($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;
}
函数正在起作用,但问题是在实现此问题之后,Germam字符不再显示。他们显示出"�"。您能帮我找到问题吗?我尝试了其他方法来缩小HTML但获得相同的proble。
也许发生了,因为您没有向正则添加Unicode标志支持。
无论如何,我编写一个代码以缩小:
function sanitize_output($buffer, $type = null) {
$search = array(
'/>[^S ]+/s', // strip whitespaces after tags, except space
'/[^S ]+</s', // strip whitespaces before tags, except space
'/(s)+/s', // shorten multiple whitespace sequences
'/<!--(.|s)*?-->/', // Remove HTML comments
'#/*(.|s)**/#Uu' // Remove JS comments
);
$replace = array(
'>',
'<',
' ',
'',
''
);
if( $type == 'html' ){
// Remove quets of attributs
$search[] = '#(w+=)(?:"|')((S|.|-|/|_|(|)|w){1,8})(?:"|')#u';
$replace[] = '$1$2';
// Remove spaces beetween tags
$search[] = '#(>)s+(<)#mu';
$replace[] = '$1$2';
}
$buffer = str_replace( PHP_EOL, '', preg_replace( $search, $replace, $buffer ) );
return $buffer;
}
研究后,我找到了这个解决方案。这将在一行中缩小完整的HTML。
function pt_html_minyfy_finish( $html ) {
$html = preg_replace('/<!--(?!s*(?:[if [^]]+]|!|>))(?:(?!-->).)*-->/s', '', $html);
$html = str_replace(array("rn", "r", "n", "t"), '', $html);
while ( stristr($html, ' '))
$html = str_replace(' ', ' ', $html);
return $html;
}
希望这对某人有帮助!