Regular Expressions 101

Community Patterns


Valid HTML Tag Pattern


Regular Expression
PCRE2 (PHP >=7.3)

<(\w+)(?: \w+ ?= ?("|')?.*\2 ?)*(?:(?:>(?:.*)<\/\1>)|(?:\/>))


Valid HTML Tag Pattern

Which HTML tags are considered invalid:

  • Tags ending with a different tag than what it started. Example: <p>Hello</a>
  • Tags with open attributes (or closed with a different type of quote). Examples: <p style="color:red>Hello</p> or <p style="color:red'>Hello</p>

Which HTML tags are considered valid:

  • Tags ending with the same tag
  • Tags with closed attributes


  • This pattern does not support html tags inside of others, as it may match the whole parent element's tag.
  • This pattern does match unexistent html tags, which is not worth removing because it would make the pattern too long and also because custom html tags exist.
  • This pattern does support tags that look like this: <img src=""/>
Submitted by Ninja - 2 months ago (Last modified 2 months ago)