ShibSta Posted January 30, 2007 Share Posted January 30, 2007 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 https://forums.phpfreaks.com/topic/36282-finding-image-url-from-css-background-imageurl/ Share on other sites More sharing options...
dustinnoe Posted January 30, 2007 Share Posted January 30, 2007 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]<?phppreg_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 https://forums.phpfreaks.com/topic/36282-finding-image-url-from-css-background-imageurl/#findComment-172533 Share on other sites More sharing options...
effigy Posted January 30, 2007 Share Posted January 30, 2007 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 https://forums.phpfreaks.com/topic/36282-finding-image-url-from-css-background-imageurl/#findComment-172764 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.