2010-01-06 44 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

相关问题