Parse CSS with PHP

For one of our recent projects we have been looking at Optimising Cascading Style Sheet files. After researching around the subject we found nothing that really suited our needs so we decided to give it a go ourselves.

The first step was to build a list of all the appropriate Style Sheets, as we are only dealing with Screen media we can discount the others such as; print and aural. After we had our appropriate list, it is easy to work out the Cascade path by using which ever styles are applied last and working backwards.

We decided to firstly concatenate all the CSS files into one in the order of which the appear, thus giving us one super Style Sheet file. We then proceeded to strip out all the \r\n characters (thats Carriage Return and Newline), after this we then used a Regex to remove the comments.

After we have our sanitised Style Sheet we then decided to go one step further and do the job of a Web Browser and rewrite the file to have clean blocks, with only their inherited styles in them.

So for example a sloppily written CSS file may have the following case:

ln 5:
#banner{
       font-size:1em;
       color:red;
}

ln 300
#banner{
       font-size:0.9em;
       font-weight:bold;
}

This would be rewritten to read the following:

ln 300
#banner{
       color:red;
       font-size:0.9em;
       font-weight:bold;
}

We have attached our "cssarray class" source code below, htis is only part of the project as we cant post the whole thing. However this class should be useful for building Styles into a PHP array.

The output looks like the following, $var[int val][string css selector][int val]:

<?php Array ( [0] => Array ( [.node-unpublished ] => Array ( [0] => background-color#fff4f4 ) ) [1] => Array ( [.preview .node ] => Array ( [0] => background-color: #ffffea ) ) [2] => Array ( [#node-admin-filter ul ] => Array ( [0] => list-style-type: none [1] => padding: 0 [2] => margin: 0 [3] => width: 100% ) ) )?>
Author: 
Luke Tarplin
AttachmentSize
cssarray.class.php File (in text mode)1.6 KB
Valid XHTML 1.0 Strict