对样式表进行压缩,有两个潜在的原因:
function compact_css($css_text) { $lines = preg_split('/[\r\n]+/',$css_text); for($i=0,$n=count($lines); $i<$n; $i++){ $line = trim($lines[$i]); $line = preg_replace("/\/\/(.*)/",'',$line); // single line comment $line = preg_replace('/\s+/', ' ', $line); // merge white space $line = str_replace(': ',':',$line); $line = str_replace('; ',';',$line); $lines[$i] = $line; } $str = implode('',$lines); $str = preg_replace("/\/\*(.*?)\*\//","",$str); // multiple line commment return '/* '.date('c').' */'.$str; }
利用上面的代码很容易实现对Smary模版中内嵌的样式表进行压缩。
function smarty_block_css($param, $content, &$smarty) { if($repeat) return; // open tag if($_GET['_debug']) return $content; return compact_css($content); } $smarty->registerPlugin("block",'css', 'smarty_block_css', true);