Reputation: 1442
I want to load a css file in php and then create an array of all the background images with the css classes they are used in as array keys ignoring all other css blocks which don't call a background image. Below is dummy code but I guess it would look something like this:
function makeArrayOfBackroundImages($css) {
$foo = someRegExKungfu;
foreach ($foo as $class => $background) {
$bar[] = $class => $background;
}
return $bar;
}
$css = file_get_contents('http://www.mysite.com/global.css');
$css = makeArrayOfBackroundImages($css);
So for the following css content:
.content1 {
background-image: url("http://mycdn.com/images/image1.png");
}
.content2 {
background-image: url("http://mycdn.com/images/image2.png");
}
.content3 {
background-image: url("http://mycdn.com/images/image3.png");
}
.content4 {
margin:20px;
border:1px solid #000;
}
The array would look something like this: (Note only the classes which had background images are featured)
[0] => Array
(
[content1] => http://mycdn.com/images/image1.png
[content2] => http://mycdn.com/images/image2.png
[content3] => http://mycdn.com/images/image3.png
)
The reason I am doing this is because I am building a script to test the download speed of a page and for it to be a true test I also want to download all the background images which are used on the homepage however there are other classes and background images listed in the css which are used on pages other than the homepage. I have an array of all the classes used on the homepage by using the following code:
@$dom->loadHTML('http://www.mysite.com');
$elems = $dom->getElementsByTagName('*');
foreach ($elems as $elm) {
if ($elm->hasAttribute('class')) {
$classes[] = $elm->getAttribute('class');
}
}
So once I have the classes used on the page from the above code and an array of all the background images with the class names I will then download the background images which I have a matching class name for. Hope that makes sense.
Upvotes: 0
Views: 453
Reputation: 7195
Try this function:
function makeArrayOfBackroundImages($css) {
if (!preg_match_all('/\.([a-z\d_]+)\s*\{[^{}]*url\("?([^()]+)"?\)?/i', $css, $arr)) return array();
return array_combine($arr[1], $arr[2]);
}
Note: It extract only one (first) image url per class. So it doesn't intended for work with multiple background images.
Upvotes: 1