PHP Preg 匹配 - 获取包装值

PHP Preg match - get wrapped value

我想使用预匹配提取所有换行的文本值

所以

background: url("images/gone.png");
color: #333;
...

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

从上面的字符串, 我要抢

images/gone.png
images/good.png

正确的命令行是什么?

http://www.phpliveregex.com/p/e3u

这个正则表达式可以做到这一点:

/^background: url\("(.*?)"\);$/

最好学习一些正则表达式,值得花时间: http://regexone.com/

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

正则表达式将获取所有出现在双引号中的字符串。

如果您只想获取背景,我们可以在正则表达式模式中添加相同的字符串。

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

在 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] :)