Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minify CSS using preg_replace

I'm trying to minify multiple CSS files using preg_replace. Actually, I'm only trying to remove any linebreaks/tabs and comments from the file. the following works for me:

$regex = array('{\t|\r|\n}', '{(/\*(.*?)\*/)}');
echo preg_replace($regex, '', file_get_contents($file));

But I'd like to do it in a single multiline regex, like this:

$regex = <<<EOF
{(
    \t
|
    \r
|
    \n
|
    /\*(.*?)\*/
)}x
EOF;
echo preg_replace($regex, '', file_get_contents($file));

However, this does not do anything at all. Is there any way to do this?


Edit: Ok, so I'll take a look at existing minifiers, but it still leaves me with the question how I would do a multiline regex like this, because with the x-modifier multiline regexs should work fine even in php, shouldn't they?

like image 677
fresskoma Avatar asked Sep 04 '09 13:09

fresskoma


1 Answers

I'm not sure how you would do that, but here is a script my friend wrote that is pretty fast at minifying CSS:

function minimize_css($input)
{
    // Remove comments
    $output = preg_replace('#/\*.*?\*/#s', '', $input);
    // Remove whitespace
    $output = preg_replace('/\s*([{}|:;,])\s+/', '$1', $output);
    // Remove trailing whitespace at the start
    $output = preg_replace('/\s\s+(.*)/', '$1', $output);
    // Remove unnecesairy ;'s
    $output = str_replace(';}', '}', $output);
    return $output;
}
like image 193
Eddie Avatar answered Oct 08 '22 21:10

Eddie