Compressing CSS with PHP

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

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("\r\n", "\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.

If you enjoyed this article, please share it with a friend!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>