Search code examples
phpcssregextagsstrip

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_match($pattern, $string, $matches);

But this didnt work out.

Any help appreciated..


Solution

  • $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'];
    }