Search code examples
phphtmlcssregexminify

Minify a CSS file using PHP


The below code removes all newlines and spaces from a CSS file. But the problem is if the CSS file has something like this:

.sample {
    padding: 0px 2px 1px 4px;
}

Output will be :

.sample{padding:0px2px1px4px;}

I want that spaces in between (0px 2px 1px 4px).

Here's the code that I have used :

$str=file_get_contents('sample.css');

//replace all new lines and spaces
$str = str_replace("\n", "", $str);
$str = str_replace(" ", "", $str);

//write the entire string
file_put_contents('sample.css', $str);

Solution

  • For minifying CSS in PHP, it's best to use Steve Clay's Minify library. There's no point in reinventing the wheel.

    Here's a brief walkthrough on how to install and configure the library.