Jump to content

Finding image url from CSS background-image:url()


ShibSta

Recommended Posts

This is actually a little tricky since doing look behinds requires a fixed length string and you require flexability.

The first thing you need to do is narrow down to the string that is between "background-image:" and ";"

This way you are able to use a fixed lenth string to match from.
[code]
<?php
$var = "background-image: url(images/image.gif);";

preg_match("/(?<=background\-image\:).+(?=;)/", $var, $matches);

// Returns " url(images/image.gif)" in the variable $matches[0]
?>
[/code]
Now you regex out the image url by grabbing everything between "(" and ")"
[code]
<?php
preg_match("/(?<=\().+(?=\))/", $matches[0], $matches);

$image = $matches[0];

// Returns "images/image.gif"
?>
[/code]

All I did was avoid having to match "url" and the whitespaces surrounding it.


How this helps you out!
Here's some more flexibility:

[code]
<pre>
<?php
$tests = array(
'background-image: url(images/image1.gif);',
'background-image: url (images/image2.gif);',
'background-image : url(images/image3.gif);',
'background-image : url (images/image4.gif);',
'background-image : url ( images/image5.gif );',
);

foreach ($tests as $test) {
preg_match('/(?<=background-image)\s*:\s*url\s*\(\s*(\S+)\s*\);/', $test, $matches);
echo $matches[1], '<br>';
}
?>
</pre>

[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.