Reputation: 1848
So I'm trying to write a PHP script that does something similar to http://unused-css.com/ - Basically finding all unused CSS on my site and removing it to create a "clean" CSS file.
I use the Firefox Plugin 'Dust me' to crawl the site and show all selectors that aren't used.
The Dustme plugin returns the unused selectors in the following format:
#header #nav
#header #nav p
#header #nav p a
etc
So I have my PHP script as the following:
<?php
//My site CSS (compressed) -- a small test sample
$allcss =
"body{color:#1c4866;font:13px/16px;}
#header #nav {float: left;}
#header #nav p {font-weight: bold;}
#header #nav p a {color: blue;}
input,textarea,select{font:13px/16px;color:#999;}";
//A sample of unused CSS selectors as returned by The Dustme plugin
$unusedcss =
"#header #nav
#header #nav p
#header #nav p a";
//and the code:
$rules = preg_split ('/$\R?^/m', $allcss); //Create array from all site css
$remove = preg_split ('/$\R?^/m', $unusedcss); //Create array from unused CSS selectors
$final = array();
foreach ($rules as $rule)
{
if (!in_array(substr($rule, 0, strpos($rule, " ")), $remove) )
$final[] = $rule .= "<br />";
}
echo implode("\n", $final);
When I paste the result of the final echo into a CSS file, a load of the CSS has been removed, even the CSS that is used on the site.
Can anyone help me identify the issue? Sorry I can't be of more help as to where the problem lies.
Upvotes: 4
Views: 3068
Reputation: 600
Have you tried replacing:
if (!in_array(substr($rule, 0, strpos($rule, " ")), $remove) )
$final[] = $rule .= "<br />";
with:
if (!in_array(substr($rule, 0, strpos($rule, " {")), $remove) ) {
$final[] = $rule .= "<br />";
}
I tried this locally and in $final all entries present in $remove where gone.
Upvotes: 1