Remove unused CSS from a site using a PHP script

So, I'm trying to write a PHP script that does something similar to http://unused-css.com/ - Basically find all the unused CSS on my site and delete it to create a β€œclean” CSS file.

I use the Firefox Plugin 'Dust me' to crawl the site and display all selectors that are not in use.

The Dustme plugin returns unused selectors in the following format:

#header #nav #header #nav p #header #nav pa etc 

So, I have a PHP script as follows:

 <?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 pa {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 pa"; //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 the CSS file, the CSS load has been deleted, even the CSS that is used on the site.

Can someone help me identify the problem? Sorry, I can no longer help where the problem is.

+4
source share
1 answer

You tried to replace:

 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 the entries were in $ remove, where they went.

+1
source

All Articles