;或正则表达式中的语句不起作用

时间:2016-09-07 10:05:14

标签: php

我有两个html标签,如:

$data ='<div style="background:url(img/img.jpg);color:blue"><div style="background-image:url(img/img2.jpg);color:black"></div></div>';

我使用正则表达式获取图像路径,如:

if( preg_match_all("/background-image:url\((.*?)\);/", $data, $backgroundImg) || preg_match_all("/background:url\((.*?)\);/", $data, $backgroundImg) )

但每当我打印$ backgroundImg时,它只显示第一个

Array
(
    [0] => Array
        (
            [0] => background-image:url(images/background.jpg);
        )

    [1] => Array
        (
            [0] => images/background.jpg
        )

)

如何获得第二个网址。

2 个答案:

答案 0 :(得分:0)

试试这个:

$data = '<div style="background:url(img/img.jpg)"><div style="background-image:url(img/img2.jpg)"></div></div>';

preg_match_all("/background(?:-image)?:url\(([^)]+)\)/", $data, $backgroundImg);

var_export($backgroundImg);

输出:

array (
    0 =>
        array (
            0 => 'background:url(img/img.jpg)',
            1 => 'background-image:url(img/img2.jpg)',
        ),
    1 =>
        array (
            0 => 'img/img.jpg',
            1 => 'img/img2.jpg',
        ),
)
正则表达式中的

(?:表示不执行任何捕获的子模式

答案 1 :(得分:0)

<?php
    $data ='<div style="background:url(img/img.jpg)"><div style="background-image:url(img/img2.jpg)"></div></div>';

    if(preg_match_all('~\bbackground(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\)~i',$data,$matches)){
        $images = $matches['image'];
        print_r($images);   
    }

?>

<强>结果:

Array
(
    [0] => img/img.jpg
    [1] => img/img2.jpg
)