Minify CSS files using PHP

Recently I needed a PHP script to minify my CSS files. There are many tools out there but the process was complex.
So I did found a PHP function that compress the CSS files. The process is done using preg_replace PHP function.

In order to save your precious bandwidth, you should compress your css files. Doing so is not hard at all using this snippet.

Create a file named style.php(or call it how you like). In that file include the following function:

header('Content-type: text/css');
function compress($buffer) {
  /* remove comments */
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  /* remove tabs, spaces, newlines, etc. */
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
  return $buffer;
/* your css files */


Paste the code in a file named style.php. Don’t forget to include your css files (As seen on line 11 in the example). Once done, open your HTML document and import style.php as you’ll import a css stylesheet:
style.php will contain all your css stylesheets, compressed.

<link rel="stylesheet" href="style.php" type="text/css" media="all" />

One thought on “Minify CSS files using PHP

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.