CSS Minify – Simplest and fastest code in PHP

For a recent project I was looking for a simple solution to reduce the size of a css file (minimize), I needed something like this to insert the code in html inline-mode.

I found all kinds of suggestions online, some of which were more perfect and more universal, but the solutions didn’t seem right to me, they were too resource consuming and after some tests I came to the conclusion that they were not worth it.

So I made myself a small and fast php function for minify css that works for my needs and I had no problems with it!

function byrevMinifyCSS(&$data) {
    // remove comments (safe)
    $data = str_replace(['/*','*/'],['0¿0','1¿1'],$data);
    $data = preg_replace("/0¿0.*?1¿1/s","",$data);
    // minify
    $data = preg_replace('/\s+/', ' ', $data);
}

Instead of the function, you can use an inline code variant, like the one below, maybe it’s more handy. But as resources, the inline version uses more… it’s about memory stack!

$data = preg_replace('/\s+/', ' ', preg_replace("/0¿0.*?1¿1/s","", str_replace(['/*','*/'],['0¿0','1¿1'],$data)));

From the tests on a 120kbyte CSS file I concluded that in plain/text mode, a complex minify function saves 7% more code than the function I did, which is almost insignificant in production.

But to convince you that a simple code is much more advantageous, I would like to inform you that when the files are transferred in a compressed way (which is almost mandatory today), the difference is 0.3% in the advantage of a complex method. It is an illusory and counterproductive gain, considering that the complex-slow-execution of the PHP code represents the energy and the time consumed by the processor.

Happy coding.

P.S. I chose the option of returning the results in an already predefined variable through the stack (not “return”) , because again, it is counterproductive. Memory allocation for local variable, data transfer back and forth between variables and stack release consumes resources, things that only old school programmers know , the new ones don’t even realize such a thing, probably one of the reasons why all the many new applications consume more and more resources, although they have almost nothing more compared to the applications of 10 years ago, see the mobile app!

byrev Written by:

Be First to Comment

Leave a Reply

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