【问题标题】:Parsing CSS files using RegEX使用 RegEX 解析 CSS 文件
【发布时间】:2013-06-12 00:10:34
【问题描述】:

我正在处理 CSS 文件,我正在尝试遍历 CSS 文件 使用 PHP。我正在寻找的是在 url() 选择器中捕获任何图像路径,使用正则表达式(你知道更快的方法吗?)。

到目前为止,我能够找到这个表达式:url(([^)]+))
但那不是我想要的 100%。我需要一个找到 url 选择器的表达式 并捕获其中的任何内容,这意味着如果代码包含引号或单引号,它们将不会被捕获。例如:url("images/sunflower.png") 捕获的字符串应该只是:images/sunflower.png

感谢您的帮助。

【问题讨论】:

  • 这并不像最初看起来那么简单。 URL 可能包含也可能不包含在 'single'"double" 引号内,并且 URL 本身可能包含也可能不包含匹配或不匹配的括号。但是,如果 CSS 文件是您自己创建的,并且您知道它的构成,那就另当别论了。

标签: php css regex


【解决方案1】:

请不要重复造轮子,可以避免的地方...

有大量的 CSS 解析器可以在 Internet 上免费获得。如果您想知道它是如何完成的,请打开其中一个开源的,看看它是如何完成的。这是一个花了 2 分钟才找到的示例:

https://github.com/sabberworm/PHP-CSS-Parser#value

我已经向您指出了实际显示如何提取 URL 的部分。

【讨论】:

  • 谢谢。我知道这一点,不过,我想避免为简单的任务添加太多代码。我只需要那个正则表达式,因为它只用于很小的 css 文件,所以我认为使用专用解析器有点过头了。
  • 是的,这对于您的目的来说是多余的,但检查该库如何解析 CSS 可能是明智的。这将告诉你如何自己做。
【解决方案2】:

试试这个尺寸。它不适用于以url( 开头的字符串,但如果您正在解析实际的 CSS,那么无论如何在没有选择器或属性的情况下开始都是无效的。

$data =' #foo { background: url("hello.jpg"); } #bar { background: url("flowers/iris.png"); }';
$output = array();
foreach(explode("url(", $data) as $i => $a) { // Split string into array of substrings at boundaries of "url(" and loop through it
    if ($i) {
        $a = explode(")", $a); // Split substring into array at boundaries of ")"
        $url = trim(str_replace(array('"',"'"), "", $a[0])); // Remove " and ' characters
        array_push($output, $url);
    }
} 
print_r($output);

输出:

Array ( [0] => hello.jpg [1] => flowers/iris.png )

【讨论】:

  • 这正是我所需要的。非常感谢:)
【解决方案3】:

虽然我同意 bPratik 的回答,但您可能只需要:

preg_match('/url\([\'"]?([^)]+?)[\'"]?\)/', 'url("images/sunflower.png")', $matches);

/**
url\( matches the url and open bracket
[\'"]+? matches a quote if there is one
([^]+?) matches the contents non-greedy (so the next closing quote wont get stolen)
[\'"]? matches the last quote
) matches the end.
*/

var_dump($matches);
array(2) {
  [0]=>
  string(27) "url("images/sunflower.png")"
  [1]=>
  string(20) "images/sunflower.png"
}

【讨论】:

    猜你喜欢
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 2011-04-06
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2014-03-08
    相关资源
    最近更新 更多