PHP Regex删除特定的CSS Comment

PHP Regex删除特定的CSS Comment

问题描述:

I want to write the regular expression in php matching condition below:

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

Please any one give me a regular expression in php. Thanks.

我想在php匹配条件下编写正则表达式: p>

   / * 
删除此注释行1 
删除此注释行2 
 * / 
 .class1 
 {
 background:#CCC url(images / bg.png); 
} 
  
 .class2 
 {
 color:#FFF; 
 background:#666 url(images / bg.png);  / *请勿删除此注释* / 
} 
 
 / *删除此注释* / 
 .class3 
 {
 margin:2px; 
 color:#999; 
 background:#FFF  ;  / *请勿删除此评论* / 
} 
 
 ... etc 
 ... etc 
  code>  pre> 
 
 

请任何人给我一个 php中的正则表达式。 谢谢。 p> div>

If the rule is that you want to remove all comments where there is no other code on the line then something like this should work:

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

The 'm' option makes ^ and $ match the beginning and end of a line. Do you expect the comments to run for more than one line?

EDIT:

I'm pretty sure this fits the bill:

/(^|
)\s*\/\*.*?\*\/\s*/s

Do you understand what it's doing?

Codepad: http://codepad.org/aMvQuJSZ

Support multiline:

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

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

/* Remove this comment */

Regex Explanation:

^            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

Example php code:

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

Not working for multiline comments like

/*
 * Lorem ipsum
 */

This one do the job

$regex = "!/\*[^*]*\*+([^/][^*]*\*+)*/!";
$newstr = preg_replace($regex,"",$str);
echo $newstr;

http://codepad.org/xRb2Gdhy

Found here : http://www.catswhocode.com/blog/3-ways-to-compress-css-files-using-php