最近一个项目,css主文件居然到了9800行,我震惊了。
于是写了个合并相同css的php。
合并之后有点点小问题,我难得去找什么问题了,稍微改下css就ok。有个压缩功能,默认开启的,不过没试。
<?php define('CMP', $argv>1?$argv[1]:true);//压缩 if(CMP){ define('SPA',''); define('TAB',''); define('NL',''); }else{ define('SPA',' '); define('NL',"\n"); } define('TAB',"\t"); $str = file_get_contents('green1.css'); $str = preg_replace('/\/\*.*\*\//', '',$str); $str = preg_replace('/\/\/.*/', '',$str); /*echo ' ========================== '.$str.' ========================== ';*/ preg_match_all("/([^{]+)\{([^}]+)}/", $str, $out); $arr = array(); echo 'There are :'.count($out[0]).' css classes'.chr(10); for($i=0;$i<count($out[1]);$i++){ $out[1][$i] = trim($out[1][$i]); $left = substr($out[1][$i],0,1); if($left=='.'){ $left = 'dot'; $right = substr($out[1][$i],1); }else if($left=='#'){ $left = 'jin'; $right = substr($out[1][$i],1); }else { $left = 'emp'; $right = $out[1][$i]; } $cls = $left.$right; if(isset($arr[$cls])) $arr[$cls] = array(); $stys = explode(';', $out[2][$i]); for($j=0;$j<count($stys);$j++){ $tmp = explode(':', $stys[$j]); if(count($tmp)==2){ $arr[$cls][trim($tmp[0])] = trim($tmp[1]); }else if(strlen(trim($stys[$j]))>0){ echo 'Error: '.$stys[$j].chr(10); } } } $str = ''; foreach($arr as $cls=>$v){ $pre = substr($cls,0,3); $left = substr($cls,3); if($pre=='dot'){ $cls = '.'.$left; }else if($pre=='jin'){ $cls = '#'.$left; }else if($pre=='emp'){ $cls = $left; } file_put_contents('green.css', $cls.'{'.NL, FILE_APPEND); foreach ($v as $sty=>$txt) file_put_contents('green.css', TAB.$sty.':'.SPA.$txt.";".NL, FILE_APPEND); file_put_contents('green.css', '}'."\r\n", FILE_APPEND); }