使用preg_replace来缩小CSS
我试图用preg_replace缩小多个CSS文件。实际上,我只是试图从文件中删除任何换行符/制表符和评论。我以下工作:使用preg_replace来缩小CSS
$regex = array('{\t|\r|\n}', '{(/\*(.*?)\*/)}'); echo preg_replace($regex, '', file_get_contents($file));
,但我想这样做在一个多正则表达式,像这样:
$regex = <<<EOF {( \t | \r | \n | /\*(.*?)\*/ )}x EOF; echo preg_replace($regex, '', file_get_contents($file));
然而,这并不做任何事情。有没有办法做到这一点?
编辑:好了,我会看看现有minifiers,但它仍然给我留下的问题,我会怎么做一个多正则表达式这样的,因为与x修饰符多regexs应该工作正常,即使在PHP中,他们不应该?
据我所知,你不能这样做,因为当你将它分成多行时,你实际上正在改变模式。
编辑:是的,+1,因为没有重新发明轮子。
我不知道你将如何做到这一点,但这里是一个脚本,我的朋友写的,这是非常快的缩小CSS:
function minimize_css($input)
{
// Remove comments
$output = preg_replace('#/\*.*?\*/#s', '', $input);
// Remove whitespace
$output = preg_replace('/\s*([{}|:;,])\s+/', '$1', $output);
// Remove trailing whitespace at the start
$output = preg_replace('/\s\s+(.*)/', '$1', $output);
// Remove unnecesairy ;'s
$output = str_replace(';}', '}', $output);
return $output;
}
这似乎是在不的一个很好的例子重新发明轮子。几乎在互联网上的每一个网站都使用CSS,而所有大网站都以某种方式压缩它。他们的方法已经过测试和优化。如果你不需要,为什么要推出自己的产品?
Mike和Grumbo已经提出了具体的建议,但我只想指出一般原则。
是的,因为添加库依赖性总是比向您的项目添加几行代码更好。 :/ – Jacob 2014-08-06 23:13:40
这是我使用的Samstyle PHP Framework什么:
$regex = array(
"`^([\t\s]+)`ism"=>'',
"`([:;}{]{1})([\t\s]+)(\S)`ism"=>'$1$3',
"`(\S)([\t\s]+)([:;}{]{1})`ism"=>'$1$3',
"`\/\*(.+?)\*\/`ism"=>"",
"`([\n|\A|;]+)\s//(.+?)[\n\r]`ism"=>"$1\n",
"`(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+`ism"=>"\n"
);
$buffer = preg_replace(array_keys($regex),$regex,$buffer);
希望这有助于!
function minifyCSS($css){
$css = trim($css);
$css = str_replace("\r\n", "\n", $css);
$search = array("/\/\*[^!][\d\D]*?\*\/|\t+/","/\s+/", "/\}\s+/");
$replace = array(null," ", "}\n");
$css = preg_replace($search, $replace, $css);
$search = array("/;[\s+]/","/[\s+];/","/\s+\{\\s+/", "/\\:\s+\\#/", "/,\s+/i", "/\\:\s+\\\'/i","/\\:\s+([0-9]+|[A-F]+)/i","/\{\\s+/","/;}/");
$replace = array(";",";","{", ":#", ",", ":\'", ":$1","{","}");
$css = preg_replace($search, $replace, $css);
$css = str_replace("\n", null, $css);
return $css;
}
http://mhameen.blogspot.com/2010/04/crystal-script-manger-for-php.html#links
这是我个人使用的CSS:
$file_contents = file_get_contents($file);<br />
preg_replace('@({)\s+|(\;)\s+|/\*.+?\*\/|\[email protected]', '$1$2 ', $file_contents);
更好地利用压缩像*放气*或* gzip的*。这会给你更好的结果。 – Gumbo 2009-09-04 13:53:04
一个例子[正则表达式CSS缩小器可以在这里找到](http://stackoverflow.com/questions/15195750/minify-compress-css-with-regex)。 – Qtax 2013-03-04 06:41:39