网上压缩css代码大部分是单行,这里用php写个遍历目录的,可以压缩css的php源码
<?php
/**
* 调用规则 如果flag为真,多行
* css.php?dir=dirname[&flag=1]
*/
set_time_limit(0);
header("Content-type:text/html;charset=utf-8");
$css=$_GET['dir'];
$flag=$_GET['flag'];
function compress_css($buffer,$flag=FALSE)
{
$buffer = preg_replace("!/\*[^*]*\*+([^/][^*]*\*+)*/!", "", $buffer) ;
$arr = array("\r\n", "\r", "\n", "\t", " ", " ", " ") ;
$buffer = str_replace($arr, "", $buffer) ;
// 去掉charset
$buffer = str_replace('@CHARSET "UTF-8";', "", $buffer) ;
if ($flag){
// 保留换行
$str='';
$buffer_array=explode('}', $buffer);
if ($buffer_array) {
foreach ($buffer_array as $key => $yb) {
if ($yb) $str.=$yb."}\r\n";
}
}
$buffer=$str;
}
return $buffer;
}
function makecss($path,$flag)
{
if (is_dir($path))
{
if ($dh = opendir($path))
{
while (($file = readdir($dh)) !== false)
{
if($file!=".."&&$file!=".")
{
if(is_dir($path."/".$file))
{
makecss($path."/".$file,$flag);
}
else
{
$content = file_get_contents($path."/".$file);
$content=compress_css($content,$flag?TRUE:FALSE);
$fp = fopen($path."/".$file, "w");
fwrite($fp, $content);
fclose($fp);
}
}
}
closedir($dh);
}
return 1;
}
}
if(makecss($css,$flag)){
echo '美化css文件成功';
}