Regular Expressions 101

Community Patterns

Match HTML comments with nested comments

0

Regular Expression
PCRE (PHP <7.3)

/
<!--(?:(?!<!--|-->).|(?R))*-->
/
gs

Description

Even if this is not valid HTML, it's more to understand the concept of recursion in patterns.

It was an answer to a Stack overflow question: https://stackoverflow.com/questions/75282404/remove-comments-from-some-generated-html-which-can-be-invalid-with-nested-commen

The idea is to use PCRE's recursive pattern to solve the problem.

Submitted by Patrick Janser - a year ago