开发者

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. 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.

I tried this:

    $pattern = "/background-image: ?.png/";
    preg开发者_StackOverflow_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".

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.

Generally, regexp is not a good tool for parsing HTML, but in this limited case it might be OK.


$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 "

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜