将css压缩到每个样式一行

simple_css
  有时候就是得这么麻烦,为了减少部分东西,自己就弄了个PHP压缩CSS的,实际上除了一堆正则表达式和字符串替换,啥都没有。作用就是将一段展开的代码压缩一下,但和单行压缩又有不同,这个没有进行单行压缩,将其中的换行只保留了一个。
  压缩后可以参考后面的CSS,如最终的效果,还是可以的,只是PHP的压缩代码还有较大的优化空间,下面的CSS通过格式化工具可以完整的还原为展开的代码,其实单行的也可以。

<?php
$content = file_get_contents($argv[1]);
$content = preg_replace("/[\\t]+/","",$content);
$content = preg_replace("/[ ]+/"," ",$content);
$content = str_replace(": ",":",$content);
$content = preg_replace("/;[\\r\\n]+/",";",$content);
$content = preg_replace("/{[\\r\\n]+/","{",$content);
$content = preg_replace("/;[\\s]+/",";",$content);
$content = preg_replace("/[\\r\\n]{2,}/","\r\n",$content);
$content = preg_replace("/,[\\s]+/",",",$content);
$content = preg_replace("/[\\s]+}/","}",$content);
$content = preg_replace("/;\\/\\*/",";\r\n/*",$content);
$content = preg_replace("/^[\\s]+/","",$content);
$content = preg_replace("/([\r\n]+)[\\s]+/","\$1",$content);
$content = preg_replace("/[\\s]+{[\\s]+/","{",$content);
$content = preg_replace("/[\\s]+}[\\s]+/","}",$content);
$content = str_replace([" }","{ "," {","} ","{/*"],["}","{","{","}","{\r\n/*"],$content);
$content = preg_replace("/([^;}])}/","\$1;}",$content);
$content=preg_replace("/\\){([^\r^\n])/","){\r\n\$1",$content);
$content = str_replace(['}}'],["}\r\n}"],$content);
echo $content;
/*-----------------------------------------------------------------------------------*
/*Headings
/*-----------------------------------------------------------------------------------*/

h1,h2,h3,h4{font-family:Tahoma,Arial,"微软雅黑","宋体";color:#000000;line-height:1.5em;font-weight:normal;text-transform:capitalize;letter-spacing:1px;}
h1{font-size:16px;height:30px;line-height:1.2em;}
h2{font-size:21px;}
h3{font-size:16px;}
h4{font-size:14px;}
h2,h3{margin-top:30px;margin-bottom:20px;}
h4{margin-top:16px;margin-bottom:22px;}
h1 a,h2 a,h3 a,h4 a{color:#000000;}
#post-header{margin-top:0;margin-bottom:22px;font-size:14px;color:#999999;background-color:#fafafa;padding:7px 0 7px 10px;}
h5{font-size:12px;color:#999999;}
h5 a{font-size:12px;}
h5 span{color:#666666;}
img.wp-smiley-select{cursor:pointer;}

26条评论在“将css压缩到每个样式一行”

  1. 现在大多数CSS压缩都给整成了一行。
    博主有想法啊,适当压缩,不但减小了体积也不影响代码查看。

    1. css本身是不乱的,但是初学者往往写的很混乱,所以就调试麻烦,还有自动生成的样式能用么?

写下你最简单的想法