Andy Berry

Musings of a Software Engineer

HomePostsAboutProjectsExperience
All posts
December 4th, 2011programming

Minify CSS with PHP


It’s always nice to have a website load quickly, especially on mobile devices. One way to help the load time is to decrease the number of bits that need to fly through the airwaves to make up the website.

Here is a quick bit of PHP that can automagically minify the CSS before it is sent – just paste it at the top of the file and change the file extension to .php. Voila!

<?php
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}
?>

Published December 4th, 2011
cssphp

Thoughts and opinions inspired by life in the Software Engineering industry

© Andy Berry, All rights reserved..

HomeCVLicenseSitemap