在CSS中的Preg_match网址

问题描述 投票:0回答:1

我想匹配我用过的这个正则表达式的css中的所有url并且它工作得非常好。

@[^a-z_]{1}url\s*\((?:\'|"|)(.*?)(?:\'|"|)\)@im

Full match: url(https://example/product.png)
Group 1: https://example/product.png

当我找到这样的网址时,问题就出现了:

background-image: url(/uploads/2019/03/product01-image(thumbnail_photo).jpg);


Full match url(/uploads/2019/03/product01-image(thumbnail_photo)
Group 1. /uploads/2019/03/product01-image(thumbnail_photo

我查看了这个主题并尝试使用一些存在的一些正则表达式进行了一些修改

preg_match to match src=, background= and url(..)

结果就是这样

@(?:url\((?:\"|'|)(.*\.(?:[a-z_]{3}))(?:\"|'|)\))@im

Full match: url(/uploads/2019/03/product01-image(thumbnail_photo).jpg)
Group 1: /uploads/2019/03/product01-image(thumbnail_photo).jpg

起初它看起来工作正常,但是当我遇到这样的情况时它会被打破:

.card-thumb__img1{display:block;width:142px;height:62px;background:url(https://example.com/product01.jpg) center center no-repeat;background-size:contain}@media (max-width:1029px).card-thumb__img2{display:block;z-index:1;background:url(https://example.com/product02.jpg) center center no-repeat #000;

Full match: url(https://example.com/product01.jpg) center center no-repeat;background-size:contain}@media (max-width:1029px).card-thumb__img2{display:block;z-index:1;background:url(https://example.com/product02.jpg)
Group 1:https://example.com/product01.jpg) center center no-repeat;background-size:contain}@media (max-width:1029px).card-thumb__img2{display:block;z-index:1;background:url(https://example.com/product02.jpg

如何解决这个问题并获得所有情况的预期结果?

编辑我必须匹配的某些类型的事件

url(https://exemples.com/fonts/lato/lato/lato-regular-webfont.ttf)
src:url(https://exemples.com/fonts/lato/lato-regular-webfont.eot?#iefix)
background:url(https://exemples.com/product/header/img.png)
background:url(/product/header/img.png)
background:url("/product/header/img.png")
background:url('/product/header/img.png')
background:url(/uploads/2019/03/0002-image(thumbnail_product).jpg)
php regex preg-match
1个回答
1
投票

对于您的示例数据,一个选项可能是递归第一个子模式(?1并使用第二个捕获组作为URL。

该网址将在捕获第2组。

url(\(((?:[^()]+|(?1))+)\))

Regex demo | Php demo

说明

  • url
  • (第一个捕获组 \(匹配( char (第二个捕获组 (?:[^()]+|(?1))+匹配1次以上不是字符类中列出的内容或递归第一个子模式并重复1次以上 )关闭第二个捕获组 \)匹配) char
  • )关闭第一个捕获组

这也将匹配网址的前导和尾随"'。在使用捕获组获取匹配项时,您可以执行另一项检查,以验证报价的起始类型是否与报价的结束类型相同。

例如:

$re = '/url(\(((?:[^()]+|(?1))+)\))/m';
$str = 'background:url("/product/header/img1.png") and background:url("/product/header/img2.png\' and background:url(/product/header/img3.png"))';

preg_match_all($re, $str, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    if (preg_match('/^([\'"]?)[^"]+\1$/', $match[2])) {
        echo trim($match[2], "'\"") . PHP_EOL;
    }
}

结果:

/product/header/img1.png
© www.soinside.com 2019 - 2024. All rights reserved.