Home » Php » php – Regex to add missing selectors to invalid CSS

php – Regex to add missing selectors to invalid CSS

Posted by: admin July 12, 2020 Leave a comment


I’m trying to transform invalid CSS like this:


and make it valid like this:


Example CSS:

a {

<!-- TEST -->

@media screen and (max-width:620px) {
/* TEST 2 */
a.test {color:blue;}
p[class="test2"] {color:green;}

My current regular expression:


Live test:


How to&Answers:

The Solution

You need to use this:


Replace with:

.missing-selector {

The (?<=\A|\}) makes sure that there only thing (other than whitespace) before the { is the start of the string or a closing }. (Thanks to Casimir et Hippolyte for pointing out the problem there.)

Here’s a regex101 demo.

Why Your Attempt Failed



doesn’t do what you think.

  • ( starts a capturing group
  • [^a-z0-9\)\];\-_] requires a character other than a-z, 0-9, ), ], ;, -, or _
  • * zero or more times
  • \{ requires the {
  • ) ends the capturing group

But it doesn’t have a ^, so it’s not tied to the start of a line, nor does it validate whatever comes before the { (which should be only the start of the string, whitespace or a }). As a result, it will match everywhere you have a series of spaces or other non-alphanumeric characters (excluding )];-_) in your sample CSS:

screenshot of regex101 demo

See this regex101 demo for a fuller explanation and example matches.