7

I want to write the regular expression in php for matching the line within a double and single quotes. Actually I am writing the code for removing comment lines in css file.

Like:

"/* I don't want to remove this line */"

but

/* I want to remove this line */

Eg:

- valid code /* comment */ next valid code "/* not a comment */" /* this is comment */

Expected result:

- valid code next valid code "/* not a comment */"

Please any one give me a regular expression in php for my requirement.

1

1 Answer 1

17

The following should do it:

preg_replace( '/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/' , '' , $theString );

Test case:

$theString = '- valid code /* comment */ next valid code "/* not a comment */" /* this is comment */';

preg_replace( '/(?!<\")\/\*[^\*]+\*\/(?!\")/' , ' ' , $theString );

# Returns 'valid code next valid code "/* not a comment */" '

Revision : 28 Nov 2014

As per comments from @hexalys, who referred to http://www.catswhocode.com/blog/3-ways-to-compress-css-files-using-php

The updated regular expression, as per that article, is:

preg_replace( '!/\*[^*]*\*+([^/][^*]*\*+)*/!' , '' , $theString );
Sign up to request clarification or add additional context in comments.

6 Comments

This has issues with the universal * selector at the end of css rules. e.g. .class > *{}
@hexalys: Thanks for the comment - I'd love to revise my answer based on this new info. Can you email me the affected CSS code at [email protected] so I can do some testing and adjust my solution?
You can test any universal selector. It may have been related to comments inside the brackets, as often do. e.g. .class > *{/*comments*/ } I ended up using the regex here.
The updated 2014 still matched this -> li:before {content: "a/*b*/";}.
^(\s*)\Q/*\E[\s\S]+?\Q*/\E$(\R+) This will be matched from beginning of line (^) and follow with zero or more space ((\s*)) ...until end ($) with new line ((\R+)). It is not perfect but it is just for prevent matching comment inside string.
|

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.