【问题标题】:Replace text between @import and \n替换 @import 和 \n 之间的文本
【发布时间】:2010-01-06 20:06:21
【问题描述】:

我使用 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?最好不要留下空格。

【问题讨论】:

标签: php css stylesheet preg-replace preg-match


【解决方案1】:

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

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

【讨论】:

  • 如果您想删除您提到的行:“在我的本地安装中,我有一些需要删除的 @import 行。”
  • 也可以将@import url('something.css'); body { color: #fff; } 替换为}
  • 短如我所愿。它按预期工作。它使用@import 删除行。谢谢!
【解决方案2】:

您可以轻松地遍历每一行,然后确定它是否以 @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;
    }
}

【讨论】:

  • 它会起作用,但感觉不是解决它的最佳方法。如果我没有找到更好的东西,我可能会使用这个。
  • 正则表达式很慢,这将允许您在线性时间内创建一个新文件,假设您在迭代每个文件时创建输出。
  • 正则表达式慢吗?因为我只在本地主机上生成 CSS 文件,所以速度对我来说并不重要。服务器加载上传的生成文件。我将使用 Inspire 的 preg_replace。还是谢谢!
【解决方案3】:

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

【讨论】:

  • 这删除了@import,但我需要删除该行。它应该删除@import 和 \n 之间的信息。
【解决方案4】:

使用 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);

应该做的工作......

【讨论】:

  • 我找到了 Inspire 写的一个较短的答案,只有一行。还是谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-05-08
  • 1970-01-01
  • 2020-02-20
  • 2013-12-31
  • 2021-10-04
  • 2020-05-23
  • 1970-01-01
  • 2015-04-08
相关资源
最近更新 更多