Minify a CSS file using PHP
Asked Answered
B

6

5

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);
Bristol answered 19/3, 2016 at 0:49 Comment(2)
aren't there many scripts out there in the net that do that already? Why reinvent the wheel? Just picked the first google entry: github.com/matthiasmullie/minifySpherulite
@Spherulite : Sometimes the fist option isn't the best option. I tried Marrias Mullie's minify library as well as MrClay's library of the same name (github.com/mrclay/minify), and I prefer the latter. Also, the latter library is much more popular. Just compare the number of watchers, stars & forks of both libraries!Blighter
B
6

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.

Blighter answered 19/3, 2016 at 1:33 Comment(0)
Z
9

There are two ways.

  1. Using ready-made libraries such as minify and CSSMin .

  2. Writing the method manually :

    function minify_css($css) {
     // Remove comments
     $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
     // Remove spaces before and after selectors, braces, and colons
     $css = preg_replace('/\s*([{}|:;,])\s+/', '$1', $css);
     // Remove remaining spaces and line breaks
     $css = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '',$css);
    
    return $css;
    }
    
Zena answered 14/5, 2023 at 10:25 Comment(0)
B
6

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.

Blighter answered 19/3, 2016 at 1:33 Comment(0)
P
3

In your code, adding the following line:

$str = preg_replace("/([0-9]*px(?!;))/", "$1 ", $str);

will add a space to any px string followed by something that is not a ;

This way you fix your code by adding spaces where you pointed out.

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

//replace all new lines and spaces
$str = str_replace("\n", "", $str);
$str = str_replace(" ", "", $str);
$str = preg_replace("/([0-9]*px(?!;))/", "$1 ", $str);

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

You could make use of any Php compression library like minify which offer complete css compression options.

I hope this helps.

Persephone answered 19/3, 2016 at 1:19 Comment(1)
The regex also removes valid spaces, e.g. from string values (e.g. content: 'Click Here!') or any non-px units (e.g. padding: 2% 5vh 3em 7mm;).Sunlit
P
2

If you want to remove the tabs and spaces around each line, but keep the spaces inside the styles. You should just explode() the whole content with \n as the token delimiter and iterate over each line and use php's trim() on it, then implode() it without any delimiter.

Presbyterian answered 19/3, 2016 at 0:57 Comment(0)
I
1

Here's a simple yet effective solution:

// Get style contents    
$style = file_put_contents('your_style.css');

// Minify it
$minified = $style;
$minified = str_replace("\n", "", $minified);
$minified = str_replace("  ", " ", $minified);
$minified = str_replace("  ", " ", $minified);
$minified = str_replace(" {", "{", $minified);
$minified = str_replace("{ ", "{", $minified);
$minified = str_replace(" }", "}", $minified);
$minified = str_replace("} ", "}", $minified);
$minified = str_replace(", ", ",", $minified);
$minified = str_replace("; ", ";", $minified);
$minified = str_replace(": ", ":", $minified);

// Write it
header("Content-type: text/css; charset: UTF-8");
echo $minified;

It will remove all empty spaces that are not necessary. It won't however remove comments or replace 4 numbers to 1 where it could be replaced, but it does great job however. Let me know if I am missing something or if you have any ideas how comment removal and/or other functions could be easily added to it.

Industrious answered 7/7, 2020 at 13:34 Comment(0)
A
1

I wrote this small preg_replace:

$css = preg_replace(
  array('/\s*(\w)\s*{\s*/','/\s*(\S*:)(\s*)([^;]*)(\s|\n)*;(\n|\s)*/','/\n/','/\s*}\s*/'), 
  array('$1{ ','$1$3;',"",'} '),
  $css
);

It collapses everything appropriately - leaving spaces within the property definition, but does not remove comments.

Abloom answered 1/5, 2021 at 6:1 Comment(1)
Doesn't work for @import url. The regex removes the space between import and url. Works well otherwise.Glauce

© 2022 - 2025 — McMap. All rights reserved.