Php 如何从样式/背景图像标记中提取图像文件名?

Php 如何从样式/背景图像标记中提取图像文件名?,php,css,regex,tags,strip,Php,Css,Regex,Tags,Strip,我发现了很多关于从img标记中分离文件名的帖子,但是没有一篇是从CSS内联样式标记中分离出来的。这是源字符串 <span style="width: 40px; height: 30px; background-image: url("./files/foo/bar.png");" class="bar">FOO</span> 但这并没有奏效 感谢您的帮助。您需要仔细阅读有关正则表达式的内容 "/background-image: ?.png/" 表示“背景图像”:可

我发现了很多关于从img标记中分离文件名的帖子,但是没有一篇是从CSS内联样式标记中分离出来的。这是源字符串

<span style="width: 40px; height: 30px; background-image: url("./files/foo/bar.png");" class="bar">FOO</span>
但这并没有奏效


感谢您的帮助。

您需要仔细阅读有关正则表达式的内容

"/background-image: ?.png/"
表示“背景图像”:可选后跟空格,后跟任何单个字符,后跟(直接)png

确切地说,您需要什么取决于您需要在标记的布局中允许多少变化,但它将类似于

其中所有的“\s*”都是可选的空格,括号捕获的内容不包含斜杠

一般来说,regexp不是解析HTML的好工具,但在这种有限的情况下,它可能还可以;
$string = '<span style="width: 40px; height: 30px; background-image: url("./files/foo/bar.png");" class="bar">FOO</span>';

$pattern = '/background-image:\s*url\(\s*([\'"]*)(?P<file>[^\1]+)\1\s*\)/i';
$matches = array();
if (preg_match($pattern, $string, $matches)) {
    echo $matches['file'];
}
$pattern='/background image:\s*url\(\s*([\'”]*)(?P[^\1]+)\1\s*\)/i'; $matches=array(); if(preg_匹配($pattern,$string,$matches)){ echo$matches['file']; }
类似的东西

$style = "width: 40px; height: 30px; background-image: url('./files/foo/bar.png');";
preg_match("/url[\s]*\(([\'\"])([^\'\"]+)([\'\"])\)/", $style, $matches);
var_dump($matches[2]);

它不适用于包含
的文件名。它基本上匹配
url()
的括号中不是

“/background image:url\([^\]+)\)/smi的任何内容。使用DOM获取样式属性,然后使用正则表达式获取背景图像值。正则表达式中的“,”应该是“.”
$string = '<span style="width: 40px; height: 30px; background-image: url("./files/foo/bar.png");" class="bar">FOO</span>';

$pattern = '/background-image:\s*url\(\s*([\'"]*)(?P<file>[^\1]+)\1\s*\)/i';
$matches = array();
if (preg_match($pattern, $string, $matches)) {
    echo $matches['file'];
}
$style = "width: 40px; height: 30px; background-image: url('./files/foo/bar.png');";
preg_match("/url[\s]*\(([\'\"])([^\'\"]+)([\'\"])\)/", $style, $matches);
var_dump($matches[2]);