php - 使用 preg_replace 缩小 CSS

标签 php regex preg-replace

我正在尝试使用 preg_replace 缩小多个 CSS 文件。实际上,我只是想从文件中删除任何换行符/制表符和注释。以下对我有用:

$regex = array('{\t|\r|\n}', '{(/\*(.*?)\*/)}');
echo preg_replace($regex, '', file_get_contents($file));

但我想在单个多行正则表达式中执行此操作,如下所示:

$regex = <<<EOF
{(
    \t
|
    \r
|
    \n
|
    /\*(.*?)\*/
)}x
EOF;
echo preg_replace($regex, '', file_get_contents($file));

但是,这根本没有做任何事情。有什么办法吗?


编辑: 好的,所以我将看看现有的缩小器,但它仍然留给我一个问题,我将如何做这样的多行正则表达式,因为使用 x-modifier multiline即使在 PHP 中,正则表达式也应该可以正常工作,不是吗?

最佳答案

我不确定你会怎么做,但这是我 friend 写的一个脚本,它在缩小 CSS 方面非常快:

function minimize_css($input)
{
    // Remove comments
    $output = preg_replace('#/\*.*?\*/#s', '', $input);
    // Remove whitespace
    $output = preg_replace('/\s*([{}|:;,])\s+/', '$1', $output);
    // Remove trailing whitespace at the start
    $output = preg_replace('/\s\s+(.*)/', '$1', $output);
    // Remove unnecesairy ;'s
    $output = str_replace(';}', '}', $output);
    return $output;
}

关于php - 使用 preg_replace 缩小 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1379277/

相关文章:

javascript - else 语句逻辑未运行

php - 使用 MySQL 和 PHP 在多个表中搜索

php - 如何将mysql语句中的变量设置为下拉列表中的用户选择

php - oci_execute() : OCI_SUCCESS_WITH_INFO: ORA-24344 using a trigger/sequence to auto increment an oracle table error

python - 如何在 python 中编写正则表达式来识别字符串中的日期

javascript - 允许非 ASCII 字符的(类似 twitter 的)主题标签的正则表达式

python - 需要帮助理解带有正则表达式和 cURL 的 python 片段

php - 删除字符串,除非有空格

字符串和引号之间的 PHP preg_replace

php - Preg_replace 错误,当使用不同的语言文本时。 (摆脱线条)