PHP Preg match-获取包装值

PHP Preg match-获取包装值,php,regex,preg-match,Php,Regex,Preg Match,我想使用preg match提取所有包装的文本值 所以 从绳子上面, 我要抢 images/gone.png images/good.png 此操作的正确命令行是什么? 此正则表达式将执行以下操作: /^background: url\("(.*?)"\);$/ 最好了解一些关于regex的知识,这是值得的: 正则表达式将获取包含在双引号中的所有字符串 如果您只需要获取背景,我们可以在regex模式中添加相同的字符串。在php中,您应该: $regex = '~background:\s*

我想使用preg match提取所有包装的文本值

所以

从绳子上面, 我要抢

images/gone.png
images/good.png
此操作的正确命令行是什么?

此正则表达式将执行以下操作:

/^background: url\("(.*?)"\);$/
最好了解一些关于regex的知识,这是值得的:

正则表达式将获取包含在双引号中的所有字符串


如果您只需要获取背景,我们可以在regex模式中添加相同的字符串。

在php中,您应该:

$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 ) )
$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);

因此,带有URL的列表将位于
$matches[1]
:)

您可以使用sabberworm CSS解析器:有几个CSS属性可以括在引号之间(例如属性
内容
)。另外,
url(“images/gone.png”)
可以用单引号写,也可以不用引号写。如果我理解正确的话,这里的意思是-1。在单引号内。2.在双引号内。3.括号内。如果我误解了,请纠正我。图像路径周围总是有括号,只有引号是可选的。但正如我在评论中所说,最好使用解析器,因为CSS文件中有太多陷阱。
$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 ) )
$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"
  }
}