4

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.

3
  • 1
    There is a python app called mincss available on GitHub that could be useful. Commented Mar 8, 2013 at 13:13
  • What I'm trying to do would show ALL unused CSS - the Dustme plugin crawls the whole site, not just one page. Commented Mar 8, 2013 at 13:27
  • @l2aelba what are you talking about?? Commented Mar 8, 2013 at 14:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, I only have your example to work with and for that it seems to do the job. It's a bit hard to figure out why rules aren't being removed without knowing the original and unused CSS you're working with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.