简体   繁体   中英

;Or statement in Regular expression not working

i have two html tag like :

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

I used regular expression to get the image path like :

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

But whenever i print the $backgroundImg it shows only the 1st one

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

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

)

how to get the 2nd one url also.

try this:

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

Outputs:

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',
        ),
)

(?: in regex means the subpattern that does not do any capturing

<?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);   
    }

?>

Results:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM