Compressing CSS with PHP

Here is a short PHP function that removes comments and whitespace from your CSS.  If you happen to be generating your stylesheet dynamically, try wrapping this around the output to reduce the overall size.

function compress_css($css) {
    // Remove comments
    $css = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $css);
    // Remove whitespace
    $css = str_replace(array("rn", "r", "n", "t", '  ', '    ', '    '), '', $css);
    return $css;
}

Dont' forget that, if you are using PHP to output CSS, you'll need to serve the correct headers:

header("Content-type: text/css");
header("Expires: " . gmdate("D, d M Y H:i:s", (time() + 604800000)) . " GMT");

The second line tells the browser to cache the styles for seven days. You can adjust that accordingly based on your preferences.

Author avatar

About the author

Creator of Surreal CMS, Postleaf, and other web things.

Need to get in touch? Catch me on Twitter.