PHP – Minify CSS

The given PHP example can simplify the css and can remove extra spaces, tabs etc from a given css.

Code Example:
<?php
/* Minify CSS */
function minifyCSS($string){
 
    /* Strips Comments */
    $string = preg_replace('!/\*.*?\*/!s','', $string);
    $string = preg_replace('/\n\s*\n/',"\n", $string);
 
    /* Minifies */
    $string = preg_replace('/[\n\r \t]/',' ', $string);
    $string = preg_replace('/ +/',' ', $string);
    $string = preg_replace('/ ?([,:;{}]) ?/','$1',$string);
    return $string;
}

$string = "<style type='text/css'>
	body {
		background-color: #FFFFFF;
		color: #000000;
		font-family: Verdana, Tahoma, Arial;
		font-size: 12px;
	}
	td {
		color: #000000;
		font-family: Verdana, Tahoma, Arial;
		font-size: 12px;
	}</style>";

echo minifyCSS($string);

?>

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

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