<?php

// live demo @ http://www.hieta.fi/aatu/lab/minifier/minify.php

function minify_css($css, $tofile = null) {
    $css = preg_replace("/\/\*[\s\S]*?\*\//", "", $css);
    $css = preg_replace("/\s\s+/", " ", $css);
    $css = preg_replace("/\s([{};.])/", "\\1", $css);
    $css = preg_replace("/([{}:;,])\s/", "\\1", $css);
    $css = preg_replace("/;}/", "}", $css);
    $css = preg_replace("/\\n|\\t/", "", $css);
    
    if ($tofile != null)
        return file_put_contents($tofile, $css);
    
    return $css;
}

function minify_css_file($fromfile, $tofile=null) {
    $css = file_get_contents($fromfile) or die("failed to load {$fromfile}");
    
    if($tofile == null)
        $tofile = "minified_".$fromfile;
    
    return minify_css($css, $tofile);
}

?>
<?php
// example, feel free to remove:
if(basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])):

$css = file_get_contents("minify_example.css");

// vars to measure exec time and size difference
$starttime = microtime(true);
$oldlen = strlen($css);

$css_minified = minify_css($css);

$minifiedlen = strlen($css_minified);
$difference = $oldlen - $minifiedlen;
$exectime = microtime(true) - $starttime;
$diffpros = ($difference / $oldlen) *100;
    
echo "
<pre>
Orginal size: {$oldlen} bytes.
Minified size: {$minifiedlen} bytes.
Minified CSS is {$difference} bytes ({$diffpros}%) smaller.
Execution time: {$exectime} sec.

(CSS is from my wip website, build on top of h5bp)

Minified CSS:
--------------------------------------------------------------------------------
{$css_minified}
--------------------------------------------------------------------------------


Orginal CSS:
--------------------------------------------------------------------------------
{$css}
--------------------------------------------------------------------------------
</pre>
";
endif;
?>