0

我使用 PHP。

我正在研究一种自动将我所有的 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 或更好的方法替换 @import-lines?最好不要留下空白间隙。

4

4 回答 4

3

这应该通过正则表达式处理它:

preg_replace('/\s*@import.*;\s*/iU', '', $text);
于 2010-01-06T20:15:43.853 回答
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;
    }
}
于 2010-01-06T20:09:48.117 回答
0

str_replace("@import", '', $str);

于 2010-01-06T20:08:19.930 回答
0

使用 preg_match 找到 @import 可能更容易,然后使用 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);

应该做的工作...

于 2010-01-06T20:15:27.397 回答