Regular Expressions 101

Community Patterns

1...34567...886

Valid HTML Tag Pattern

1

Regular Expression
PCRE2 (PHP >=7.3)

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

Description

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

Notes

  • 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="https://example.com"/>
Submitted by Ninja - 2 months ago (Last modified 2 months ago)