使用 PHP 缩小 CSS 文件

Minify a CSS file using PHP

下面的代码从 CSS 文件中删除所有换行符和空格。但问题是如果 CSS 文件有这样的东西:

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

输出将是:

.sample{padding:0px2px1px4px;}

我想要中间的空格 (0px 2px 1px 4px)。

这是我使用过的代码:

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

如果您想删除每行周围的制表符和空格,但保留样式内的空格。您应该只 explode() 整个内容 \n 作为标记分隔符并遍历每一行并在其上使用 php 的 trim() ,然后 implode() 它没有任何分隔符。

在您的代码中,添加以下行:

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

会将 space 添加到任何 px 字符串后跟不是 ;

这样您就可以通过在您指出的地方添加 space 来 修复 您的代码。

$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(?!;))/", " ", $str);

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

您可以使用任何 Php 压缩库,例如 minify,它提供完整的 css 压缩选项。

希望对您有所帮助。

要在 PHP 中缩小 CSS,最好使用 Steve Clay's Minify library。重新发明轮子是没有意义的。

Here 简要介绍了如何安装和配置库。

这里有一个简单而有效的解决方案:

// 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;

它将删除所有不需要的空格。但是,它不会删除评论或将 4 个数字替换为 1 个可以替换的数字,但它确实做得很好。 让我知道我是否遗漏了什么,或者如果您有任何想法如何删除评论 and/or 其他功能可以很容易地添加到它。

我写了这个小preg_replace:

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

它会适当折叠所有内容 - 在 属性 定义中保留空格,但不会删除注释。