我正在尝试使用 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/