简体   繁体   English

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

[英];Or statement in Regular expression not working

i have two html tag like : 我有两个像这样的html标签:

$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 但是每当我打印$ backgroundImg时,它只显示第一个

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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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