PHP Regex删除特定的CSS注释


PHP Regex to remove specific CSS Comment

我想在php中编写匹配条件的正则表达式:

   /* 
    Remove this comment line 1
    Remove this comment line 2
   */
   .class1
   {
      background:#CCC url(images/bg.png);
   }
   .class2
   {
      color: #FFF;
      background:#666 url(images/bg.png); /* DON'T remove this comment */
   }
   /* Remove this comment */
   .class3
   {
      margin:2px;
      color:#999;
      background:#FFF; /* DON'T Remove this comment */
   }
    ...etc
    ...etc

请任何人给我一个正则表达式在php。谢谢。

如果规则是要删除行中没有其他代码的所有注释,则应该这样做:

/^('s*'/'*.*?'*'/'s*)$/m

'm'选项使^和$匹配行首和行尾。您希望注释运行超过一行吗?

编辑:

我很确定这符合要求:

/(^|'n)'s*'/'*.*?'*'/'s*/s

你明白它在干什么吗?

不支持像

这样的多行注释
/*
 * Lorem ipsum
 */

这个就够了

$regex = "!/'*[^*]*'*+([^/][^*]*'*+)*/!";
$newstr = preg_replace($regex,"",$str);
echo $newstr;
http://codepad.org/xRb2Gdhy

在这里找到:http://www.catswhocode.com/blog/3-ways-to-compress-css-files-using-php

Codepad: http://codepad.org/aMvQuJSZ

支持多行:

/* Remove this comment 
multi-lane style 1*/
/* Remove this comment 
multi-lane style 2
*/
/* Remove this comment */

正则表达式的解释:

^            Start of line
's*          only contains whitespace
'/'*         continue with /*
[^('*'/)]*   unlimited number of character except */ includes newline
'*'/         continue with */
m            pattern modifier (makes ^ start of line, $ end of line

示例php代码:

$regex = "/^'s*'/'*[^('*'/)]*'*'//m";
$newstr = preg_replace($regex,"",$str);
echo $newstr;