2009-09-04 49 views
4

我試圖用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中,他們不應該?

+2

更好地利用壓縮像*放氣*或* gzip的*。這會給你更好的結果。 – Gumbo 2009-09-04 13:53:04

+0

一個例子[正則表達式CSS縮小器可以在這裏找到](http://stackoverflow.com/questions/15195750/minify-compress-css-with-regex)。 – Qtax 2013-03-04 06:41:39

回答

5

有一些實用工具可以滿足您的需求併爲您節省潛在的錯誤正則表達式。

YUI compressor支持縮小CSS和JavaScript文件。

在編寫自己的作品之前,您可能希望考慮這個或其他現有的選項。

0

據我所知,你不能這樣做,因爲當你將它分成多行時,你實際上正在改變模式。

編輯:是的,+1,因爲沒有重新發明輪子。

7

我不知道你將如何做到這一點,但這裏是一個腳本,我的朋友寫的,這是非常快的縮小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; 
} 
1

這似乎是在的一個很好的例子重新發明輪子。幾乎在互聯網上的每一個網站都使用CSS,而所有大網站都以某種方式壓縮它。他們的方法已經過測試和優化。如果你不需要,爲什麼要推出自己的產品?

Mike和Grumbo已經提出了具體的建議,但我只想指出一般原則。

+0

是的,因爲添加庫依賴性總是比向您的項目添加幾行代碼更好。 :/ – Jacob 2014-08-06 23:13:40

0

這是我使用的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); 

希望這有助於!

0
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

2

這是我個人使用的CSS:

$file_contents = file_get_contents($file);<br /> 
preg_replace('@({)\s+|(\;)\s+|/\*.+?\*\/|\[email protected]', '$1$2 ', $file_contents);