0

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.

1
  • Why don't you remove all comments ? Commented Nov 24, 2011 at 6:47

3 Answers 3

1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

actually: /(^|\n)\s*\/*.*?*\/\s*(\n|$)/s
/\n\s*\/*.*?*\/\s*\n/s and /(^|\n)\s*\/*.*?*\/\s*(\n|$)/s not working for me , @Godwin. Produce some error when using preg_replace.
Sorry about that, I think there was something off when I cut and pasted. Check the edit in the original answer.
1

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

Comments

0

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;

1 Comment

Thanks, its work in one line comment, how about multi line comment. like: /****** Line1 line2 line3 ******/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.