Regular Expressions 101

Community Patterns

Community Library Entry

1

Regular Expression
PCRE2 (PHP >=7.3)

/
(?P<attr_name>[^:;\s]+)\s*:\s*(?P<attr_val>[^;]+(?=\b))(?:\s*;)?
/
g

Description

This regex matches every name-value pair inside a line of inline CSS. It doesn't support CSS that contains string literals (such as content: "hello world";). Therefore, only use it on simple CSS that doesn't make use of attributes which take a string literal as its value.

Parsing Rules

Every occurence of name: value; would result in a match, and the match would contain two named groups: attr_name, which stores the name of the CSS attribute (with leading and trailing whitespace removed), and attr_val, which stores the value (also with leading and trailing whitespace removed). Values that contain spaces are supported.

The inline CSS can contain line-breaks between item pairs, which would be ignored. Also, the final name-value pair would be matched correctly even if the ending semicolon is omitted.

Submitted by A-Paint-Brush - a month ago