Preg_match css 中的网址

Preg_match urls in css

我想匹配来自 css 的所有 url 我一直在使用这个正则表达式并且它工作得很好。

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

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

当我发现这样的 url 时,问题发生了:

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)

对于您的示例数据,一个选项可能是递归第一个子模式 (?1 并为 url.

使用第二个捕获组

url 将在捕获组 2 中。

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

Regex demo | Php demo

说明

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

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

例如:

$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('/^([\'"]?)[^"]+$/', $match[2])) {
        echo trim($match[2], "'\"") . PHP_EOL;
    }
}

结果:

/product/header/img1.png