PHP Preg match - 获取包裹的值

3
我想使用 preg_match 提取所有包装文本值。
因此,
background: url("images/gone.png");
color: #333;
...

background: url("images/good.png");
font-weight: bold;

从上述字符串中,我想要获取:

images/gone.png
images/good.png

这将是正确的命令行?

1
你可以使用sabberworm CSS解析器:https://github.com/sabberworm/PHP-CSS-Parser - Casimir et Hippolyte
4个回答

2

2
$pattern = '/(?:\"([^\"]*)\")|(?:\'([^\']*)\')|(?:\(([^\(]*)\))/i';
$string = '
background: url("images/gone.png1");
background: url(\'images/gone.png2\');
background: url(images/gone.png3);
color: "#333;"';
preg_match_all($pattern, $string,$matches);
print_r($matches[0]);

正则表达式将提取所有用双引号括起来的字符串。
如果只想获取背景,我们可以在正则表达式中添加相同的字符串。

有几个 CSS 属性可以用引号括起来(例如 content 属性)。另外,url("images/gone.png") 也可以用单引号或不用引号来书写。 - Casimir et Hippolyte
如果我理解正确,enclosed mean指的是:1.在单引号内。2.在双引号内。3.在括号内。如果我理解有误,请纠正我。 - Elixir Techne
图像路径周围始终有括号,仅引号是可选的。但正如我在注释中所说,最好使用解析器,因为CSS文件中有太多的陷阱。 - Casimir et Hippolyte

2
$regex = '~background:\s*url\([\"\']?(.*?)[\"\']?\);~i';
$mystr = 'background: url("images/gone.png");
color: #333;
...

background: url("images/good.png");
font-weight: bold;';
preg_match_all($regex, $mystr, $result);
print_r($result);

***Output:***
Array ( [0] => Array ( [0] => background: url("images/gone.png"); [1] => background: url("images/good.png"); ) [1] => Array ( [0] => images/gone.png [1] => images/good.png ) )

2
在php中,您应该这样做:
$str = <<<CSS
    background: url("images/gone.png");
    color: #333;

    background: url("images/good.png");
    font-weight: bold;
CSS;

preg_match_all('/url\("(.*?)"\)/', $str, $matches);
var_dump($matches);

然后,你将会看到类似于以下的输出结果:
array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(22) "url("images/gone.png")"
    [1]=>
    string(22) "url("images/good.png")"
  }
  [1]=>
  array(2) {
    [0]=>
    string(15) "images/gone.png"
    [1]=>
    string(15) "images/good.png"
  }
}

因此,包含URL的列表将在$matches[1]中 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接