Minification refers to the process of removing all unnecessary characters while leaving the core functionality of the code in tact. The end result is a new file which is smaller in size to the original, yet identical from a machine perspective. The core benefit to smaller files is that they require less bandwidth and are faster for the client to download. Although not intended, the minification profess can make code more difficult for humans to read, which is why minification can also been seen as light weight obfuscation.
Here at data·yze we use PHP to push files from our development environment to production. We opt to automate the minification process during this push step. This approach gives us all of the benefits of minimization (smaller files which require less bandwidth for the users) without the drawbacks (forcing our developers to work with giant blobs of difficult to read code).
At data·yze, minimizing CSS reduces the size of our CSS files by 20-23% on average.
Here is our minimixeCSS function.
So what's going on here?
Line 3 is the real meat of the expression. The function preg_replace() is looking for any string that matches the regular expression, \/\*((?!\*\/).)*\*\/, and removes it from the $css string. \/\* and \*\/ match the /* and */, start and end comment delimiters in CSS respectively. Both /, and * are special characters and need to be escaped. The middle part, ((?!\*\/).)*, preforms a negative look ahead. The expression matches any string (.) so long as the expression (\*\/), the CSS end comment delimiter, is not in it.
The rest of the code is pretty straight forward. Line 4 collapses white space. Line 5 removes white space where it's not needed, such as before or after a colon, brace or semicolon. Finally Line 6 removes the final semicolon since it's not needed.
If we want to be pedantic, lines 4 - 6 could be merged into a single statement using a 3 element array for all the regular expressions and another for the replacements. I, personally, prefer to have one non-trivial regular expression per line. Keeping lines separate makes the code more readable, which makes it easier to debug and modify. The code only executes when our developers are ready to push changes to production. Since the code isn't client facing, the potential improvement in performance isn't worth the hit to readability.
Let's see it in action with the following example: