Compress and output CSS

Have you ever wanted to reduce the size of your CSS files that you serve to your visitors? If so then here is a quick solution to it. This function will remove all unnecessary spaces, tabs, new line characters as well as multi- and single-line comments reducing the size of your CSS file quite significantly.

Here is the function source:

  1. <?php
  2.  
  3. /**
  4.  * Compress contents of a CSS file
  5.  *
  6.  * @param string $css Contents of a css file
  7.  * @return string
  8.  */
  9. function compressCss($css)
  10. {
  11.     // remove multiline comments, new lines, tabs and single line comments
  12.     $css = preg_replace_callback('/(\/\*.*?\*\/|\n|\t|\/\/.*?\n)/sim',
  13.         create_function(
  14.             '$matches',
  15.             'return "";'
  16.         ), $css);
  17.  
  18.     // remove all around in ",", ":" and "{"
  19.     $css = preg_replace_callback('/\s?(,|{|:){1}\s?/sim',
  20.         create_function(
  21.             '$matches',
  22.             'return $matches[1];'
  23.         ), $css);
  24.  
  25.     return $css;
  26. }

Showing 1 - 1 of 1 results