Regular Expressions 101

Community Patterns

Community Library Entry

0

Regular Expression
PCRE2 (PHP >=7.3)

/
<(?'Tag'td|th)(?'NonStyleAttributes1'(?>\s+(?!style)\w*(?>="[^"<>]*")*)*)(?>(?'SpaceBeforeStyle'\s*)\sstyle="(?!padding|[^"<>]*\spadding)(?'OtherStyling'[^"<>]*)"(?'NonStyleAttributes2'(?>\s+(?!style)\w*(?>="[^"<>]*")*)*))?(?'TagEnd'\s*>)(?!\s*(?><br(?>\s[^<>])*\/?>\s*)?<\/\k'Tag'\s*>)
/
gmi

Description

This RegEx is very specific but demonstrates a technique to find and modify HTML tags.

Finds <td> and <th> tags that:

  • Do not already have padding.
  • Are complete (i.e. have a closing tag)
  • Are not empty (nor contain only one <br> tag)

and add styling to it to give it a padding of 3 pixels between the table cells' borders and their contents.

In order to be more readable, it uses named capture groups.

  • Tag: th or td
  • NonStyleAttributes1: Substring of HTML tag attributes, if any, that are before the style attribute.
  • SpaceBeforeStyle: If contiguous whitespace characters immediately before the style attribute, this is all but the last whitespace character.
  • OtherStyling: style attribute value string that doesn't contain "padding" (and ends with a semi-colon)
  • NonStyleAttributes2: Substring of HTML tag attributes, if any, that are after the style attribute.
  • TagEnd: Anything between the last attribute and the end of the opening tag, including the ending >.

If it finds a match so far, it looks ahead to ensure there's anything between this opening tag and the closing tag besides a simple <br> tag.

If all that is matched then we have everything we need to replace the opening tag with an opening tag that contains padding by assembling the following...

  1. <
  2. Tag (th or td)
  3. NonStyleAttributes1 - attributes before the style tag, if any
  4. SpaceBeforeStyle - any extra white-space before the style tag
  5. style="padding: 3px;
  6. OtherStyling - any existing styling
  7. "
  8. NonStyleAttributes2 - attributes after the style attribute, if any
  9. TagEnd - the ending of the opening tag (any white-space and >)
Submitted by jsmart523 - 3 years ago