Jump to content

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


ShibSta

Recommended Posts

I want to find a background image from CSS, how would I go about doin' this?

preg_match('/background-image:url([b]<Image URL Would Be Here>[/b]);/', $v, $results);

(Note: There is sometimes a space between the ":" and "url" and sometimes between "url" and "(")

Thanks
Link to comment
Share on other sites

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!
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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