2

我有一个压缩 php 输出的函数,但它给我的内联 javascript 带来了问题。

我找到了一个相关主题的页面,但那里的示例不起作用:http: //jeromejaglale.com/doc/php/codeigniter_compress_html

使用 // 缩短多个空白序列时会出现问题

如果我从数组中删除这部分,则 Javascript 运行良好。

问题:

是否有可能在不需要使用MinifyTidy等其他库的情况下达到预期的结果?

功能:

/**
* [sanitize_output Compress the php output]
* @param  [type] $buffer [ Buffer = ob_get_contents(); ]
* @return [type]         [ string ]
*/
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
'/<!--(.|\s)*?-->/',    //strip HTML comments
'#(?://)?<!\[CDATA\[(.*?)(?://)?\]\]>#s', //leave CDATA alone

);
$replace = array(
'>',
'<',
'\\1',
'',
"//<![CDATA[\n".'\1'."\n//]]>",

);

$buffer = preg_replace($search, $replace, $buffer);


return $buffer;

} // End sanitize_output()

我使用它的方式:

<?php
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();

// ... Code ... Several CSS ... JS ..

$output = ob_get_contents();
ob_end_clean();
$output =  sanitize_output($output);
echo $output;
4

0 回答 0