-1

I would like to remove HTML comments from some generated content. If I use the regex /<!--(.*?)-->/ (ungreedy with the ?) then it works for most cases such as this example:

<!-- <h1> test </h1> --> not remove <!-- <h1> test 2 </h1> -->

It gets rid of the <h1> tags and leaves the "not remove" as desired.

But if the comments are nested, then it will not handle it properly as it will leave the last comment closing tag '-->'. The workaround would be to use a greedy pattern, but in this case it will not work for the first case, with multiple comments.

Example of nested comments (I know it's not valid HTML, but it's the backend which is generating it):

text <!-- something <!-- <p> test </p> --> need remove -->

I've tried to find a solution, but I don't know how to solve this. Has anyone an idea how to handle it?

Patrick Janser
  • 3,318
  • 1
  • 16
  • 18
Bálint Bakos
  • 474
  • 2
  • 5
  • 21
  • 4
    HTML doesn't allow comments to be nested. – Quentin Jan 30 '23 at 09:35
  • [Related](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Dezza Jan 30 '23 at 09:49
  • Yes i know, I hava a php backand and mix content as string, that's why this happened. this is the reason why I want to delete similar comments – Bálint Bakos Jan 30 '23 at 10:17
  • 1
    That's an [XY problem](https://en.wikipedia.org/wiki/XY_problem). Solve the actual problem (your "_back**a**nd_") instead of solving follow-up problems/symptoms. If you output HTML chunks unchecked (for unfinished comments) or without overview then improve your logic there. – AmigoJack Jan 30 '23 at 10:28
  • @BálintBakos : Did my suggestion of using a recursive pattern in my answer help you? Have you managed to get it working now? – Patrick Janser Jan 31 '23 at 08:16

1 Answers1

1

As you mentioned, it's frustrating because with the ungreedy rule you solve one case and with the greedy rule you solve the other, but you cannot solve both at the time. Well, you are lucky because PHP's PCRE engine accepts recursion :-) !

So the problem can be solved with the magic of (?R) which acts a bit like a "Copy and paste the full pattern here", as I've understood it.

The pattern will be: /<!--(?:(?!<!--|-->).|(?R))*-->/gs

You can test it here: https://regex101.com/r/fZK8VP/1

Explained:

  • <!-- matches the string "<!--".

  • (?: | )* is a non-capturing group which can be repeated several times and with two options:

    A) First option:

    • (?!<!--|-->) is a negative lookahead with two options to say don't match if it's followed by "<!--" or by "-->".

    • . matches any char.

    B) Second option: (?R) which is the entire pattern (recursion).

  • --> matches the string "-->".

I've used the s pattern modifier as the . should also match new lines in case you have some comments on several lines.

Patrick Janser
  • 3,318
  • 1
  • 16
  • 18