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);
2
  • 1
    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/minify Commented Mar 19, 2016 at 1:12
  • @Jeff : 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! Commented Mar 19, 2016 at 1:36

6 Answers 6

11

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;
    }
    
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

1 Comment

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;).
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.

Comments

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.

Comments

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.

1 Comment

Doesn't work for @import url. The regex removes the space between import and url. Works well otherwise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.