Remove unused CSS from site with PHP script


So I'm trying to write a PHP script that does something similar to - 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    

So I have my PHP script as the following:


//My site CSS (compressed) -- a small test sample
$allcss = 
#header #nav {float: left;}
#header #nav p {font-weight: bold;}
#header #nav p a {color: blue;}

//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.




Have you tried replacing:

if (!in_array(substr($rule, 0, strpos($rule, " ")), $remove) )
    $final[] = $rule .= "<br />";


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.

People are also looking for solutions to the problem: Uncaught Syntax Error with Javascript and Php Strings


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.