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.

deceze
  • 510,633
  • 85
  • 743
  • 889
user285146
  • 111
  • 1
  • 3
  • 7
  • 6
    You may simply want to use an already existing compressor instead of parsing CSS yourself, unless you have some very specific reason to do so. See [CSS - How to remove comments and make CSS one line](http://stackoverflow.com/questions/3603052/css-how-to-remove-comments-and-make-css-one-line). Also: [Don't Do It](http://stackoverflow.com/questions/2575810/comments-in-string-and-strings-in-comments/2575830#2575830). – deceze Oct 21 '10 at 05:09

1 Answers1

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 );
Luke Stevenson
  • 10,357
  • 2
  • 26
  • 41
  • 1
    This has issues with the universal `*` selector at the end of css rules. e.g. `.class > *{}` – hexalys Nov 14 '14 at 23:12
  • @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 stackoverflow@lucanos.com so I can do some testing and adjust my solution? – Luke Stevenson Nov 24 '14 at 04:37
  • 1
    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](http://www.catswhocode.com/blog/3-ways-to-compress-css-files-using-php). – hexalys Nov 24 '14 at 04:53
  • 1
    The updated 2014 still matched this -> `li:before {content: "a/*b*/";}`. – vee Jan 06 '21 at 08:13
  • ```^(\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. – vee Jan 06 '21 at 08:42
  • @vee that is an extreme edge case. Worth noting, of course, but as you said, even a solution which addresses this isn’t perfect. – Luke Stevenson Jan 06 '21 at 09:00