[英]How to extract image filename from style/background-image tag?
I found lots of posts regarding estracting a filename from an img-tag, but none from a CSS inline style tag. 我发现了很多关于从img-tag提取文件名的文章,但没有从CSS inline style标记中提取文件名的文章。 Here's the source string 这是源字符串
<span style="width: 40px; height: 30px; background-image: url("./files/foo/bar.png");" class="bar">FOO</span>
What I want to get is bar.png . 我想要得到的是bar.png 。
I tried this: 我尝试了这个:
$pattern = "/background-image: ?.png/";
preg_match($pattern, $string, $matches);
But this didnt work out. 但这没有解决。
Any help appreciated.. 任何帮助表示赞赏。
You need to read up about regular expressions. 您需要阅读有关正则表达式的信息。
"/background-image: ?.png/"
means "background-image:" followed optionally by a space, followed by any single character, followed (directly) by "png". 表示“背景图像:”,其后可以有一个空格,然后是任何单个字符,(直接)后是“ png”。
Exactly what you need depends on how much variation you need to allow for in the layout of the tag, but it will be something like 正是你所需要取决于你需要多少变化,以允许在标签的布局,但它会是这样的
"/background-image\s*:\s*url\s*(\s*".*([^\/]+)"/
where all the "\\s*" are optional spaces, and parenthesis captures something that doesn't contain a slash. 其中所有“ \\ s *”都是可选空格,并且括号捕获不包含斜杠的内容。
Generally, regexp is not a good tool for parsing HTML, but in this limited case it might be OK. 通常,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'];
}
something along the lines 沿线的东西
$style = "width: 40px; height: 30px; background-image: url('./files/foo/bar.png');";
preg_match("/url[\s]*\(([\'\"])([^\'\"]+)([\'\"])\)/", $style, $matches);
var_dump($matches[2]);
it wont work for filenames that contain '
or "
. It basically matches anything between the parenthesis of url()
that is not '
or "
它不会为包含文件名工作'
或"
它基本上是相匹配的括号之间的任何东西url()
不是'
或"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.