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.

share|improve this question
Why don't you remove all comments ? – meotimdihia Nov 24 '11 at 6:47

2 Answers

up vote 1 down vote accepted

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:

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

Do you understand what it's doing?

share|improve this answer
/\n\s*\/*.*?*\/\s*\n/s – Godwin Nov 24 '11 at 7:04
actually: /(^|\n)\s*\/*.*?*\/\s*(\n|$)/s – Godwin Nov 24 '11 at 7:08
/\n\s*\/*.*?*\/\s*\n/s and /(^|\n)\s*\/*.*?*\/\s*(\n|$)/s not working for me , @Godwin. Produce some error when using preg_replace. – Zulkhaery Basrul Nov 24 '11 at 7:20
What's the error? I'm not getting one. – Godwin Nov 24 '11 at 7:23
Sorry about that, I think there was something off when I cut and pasted. Check the edit in the original answer. – Godwin Nov 24 '11 at 7:27

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;
share|improve this answer
Thanks, its work in one line comment, how about multi line comment. like: /****** Line1 line2 line3 ******/ – Zulkhaery Basrul Nov 24 '11 at 7:23
Multi-Lane support added example link: codepad.org/Tknf440o – Utku Yıldırım Nov 24 '11 at 7:32
ok, thanks. Its work . – Zulkhaery Basrul Nov 24 '11 at 7:34
i will add explanation later – Utku Yıldırım Nov 24 '11 at 7:36
Updated for smaller regex – Utku Yıldırım Nov 24 '11 at 7:45

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.