使用PHP缩小CSS文件

问题描述 投票:-2回答:3

下面的代码从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);
php html css regex minify
3个回答
2
投票

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

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

将为任何px字符串添加一个空格,后跟不是a的字符串;

这样,您可以通过添加指向的空格来修复代码。

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

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

我希望这有帮助。


0
投票

为了在PHP中缩小CSS,最好使用Steve ClayMinify library。重新发明轮子毫无意义。

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


-1
投票

如果要删除每行周围的制表符和空格,但保留样式中的空格。你应该explode()整个内容与\n作为标记分隔符并迭代每一行并使用php的trim(),然后implode()它没有任何分隔符。

© www.soinside.com 2019 - 2024. All rights reserved.