2010-01-06 55 views
0

我使用PHP。替換@import和 n之間的文字

我正在努力將所有CSS文件自動放到一起。我自動加載CSS文件,然後將它們保存到一個較大的文件上傳。

在我的本地安裝中,我有一些需要刪除的@import行。

它看起來像這樣:

@import url('css/reset.css'); 
@import url('css/grid.css'); 
@import url('css/default.css'); 
@import url('css/header.css'); 
@import url('css/main.css'); 
@import url('css/sidebar.css'); 
@import url('css/footer.css'); 
body { font: normal 0.75em/1.5em Verdana; color: #333; } 

如果上面的風格是一個字符串內,我的最佳方式如何更換@進口線用了preg_replace或更好?不留空白空間是很好的。

+1

你就不能使用http://code.google.com/p/minify/? – Gordon 2010-01-06 20:19:23

回答

3

這應該通過正則表達式處理:

preg_replace('/\s*@import.*;\s*/iU', '', $text); 
+0

這就是如果你想*刪除*你提到的行: 「在我的本地安裝中,我有一些@import行需要刪除。」 – Inspire 2010-01-06 20:17:08

+0

也會取代'@import url('something.css'); body {color:#fff; }'只有一個'}' – gnarf 2010-01-06 20:20:54

+0

就像我期待的那樣。它像預期的那樣工作。它使用@import刪除行。謝謝! – 2010-01-06 20:21:41

0

str_replace(「@ import」,'',$ str);

+0

刪除@import,但我需要刪除該行。它應該刪除@import和\ n之間的信息。 – 2010-01-06 20:13:02

1

您可以輕鬆遍歷每一行,然後確定它是否以@import開頭。

$handle = @fopen('/path/to/file.css', 'r'); 
if ($handle) { 
    while (!feof($handle)) { 
     $line = fgets($handle, 4096); 
     if (strpos($line, '@import') !== false) { 
      // @import found, skip over line 
      continue; 
     } 
     echo $line; 
    } 
    fclose($handle); 
} 

或者,如果您希望將文件存儲在數組中前場:

$lines = file('/path/to/file.css'); 
foreach ($lines as $num => $line) { 
    if (strpos($line, '@import') !== false) { 
     // @import found, skip over line 
     continue; 
    } 
} 
+0

它會工作,但它不覺得作爲解決它的最好方法。如果我找不到更好的東西,我可以用這個。 – 2010-01-06 20:12:06

+0

正則表達式很慢,這將允許您在線性時間內創建一個新文件,假設您在迭代每個文件時創建輸出。 – 2010-01-06 20:19:21

+0

正則表達式慢嗎?因爲我只在本地主機上生成CSS文件,速度對我來說並不重要。服務器加載上傳的生成文件。 我將使用Inspire的preg_replace。不管怎麼說,還是要謝謝你! – 2010-01-06 20:27:39

0

這可能是更容易找到使用的preg_match的@imports,然後使用str_replace函數

$str = "<<css data>>"; 
while (preg_match("/@import\s+url\('([^']+)'\);\s+/", $str, $matches)) { 
    $url = $matches[1]; 
    $text = file_get_contents($url); // or some other way of reading that url 
    $str = str_replace($matches[0], $text, $str); 
} 
替換它們

至於只剝除所有@import行:

preg_replace("/@import[^;]+;\s+/g", "", $str); 

應該做的工作......

+0

我發現一個由Inspire寫的簡短答案,只有一行。不管怎麼說,還是要謝謝你! – 2010-01-06 20:22:48

相關問題