0

Let's say I have a string like this:

$css = '.class {
    color: red;
}

/* Start Comment */
.replace {
    content: "me";
}
/* End Comment */';

How can I remove everything inside the comment, including the comment itself?

I want this result:

.class {
    color: red;
}

I've tried something like this, but it doesn't do it:

$css = preg_replace( '#(/* Start Comment */).*?(/* End Comment */)#', '', $css );

I've also tried this: https://stackoverflow.com/a/13824617/2391422

Am I missing something ridiculously obvious here?

Really appreciate any feedback - regex is something I need to study further.

2
  • * is a special character, you have to escape it if you want to match a literal *. . doesn't match the newline character \n by default. To allow it to match the newline character too, you have to use the s modifier. Commented Oct 16, 2017 at 22:19
  • Try escaping / and * Commented Oct 16, 2017 at 22:19

1 Answer 1

1

You can get this code to work by adding the DOTALL-modifier s http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

$css = preg_replace( '#(/\\* Start Comment \\*/).*?(/\\* End Comment \\*/)#s', '', $css );

Additionally, the * should be escaped to get the desired effect. The / are fine as you are using another delimiter.

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

3 Comments

/\/*.+;/s also matches your string
You don't have to use two backslashes to escape the * only one suffice. Note that you can also use the \Q...\E feature for long literal parts.
It works without but it is cleaner to always escape the backslash, even in single quotes. Besides single quotes itself the only thing to manually escape.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.