1

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

cukabeka
  • 530
  • 2
  • 9
  • 22
  • '/background-image: url\\(([^\\)]+)\\)/smi – henklein Dec 13 '10 at 12:46
  • Same solution as [Regular expression for grabbing the href attribute of an A element](http://stackoverflow.com/questions/3820666/regular-expression-for-grabbing-the-href-attribute-of-an-a-element). Use DOM to fetch the style attribute, then use a regular expression to grab the background-image value – Gordon Dec 13 '10 at 12:52

3 Answers3

2

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.

Colin Fine
  • 3,334
  • 1
  • 20
  • 32
1
$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'];
}
rik
  • 8,592
  • 1
  • 26
  • 21
0

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 "

Quamis
  • 10,924
  • 12
  • 50
  • 66