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

Questions:

I’m trying to transform invalid CSS like this:

{color:red}

and make it valid like this:

.missing_selector{color:red}

Example CSS:

a {
color:black;
background-color:blue;
}

{color:red}
<!-- TEST -->

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

My current regular expression:

/([^a-z0-9\)\];\-_]*\{)/i

Live test:

http://www.phpliveregex.com/p/eMq

How to&Answers:

The Solution

You need to use this:

/(?<=\A|\})(\s*)\{/m

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

This

/([^a-z0-9\)\];\-_]*\{)/i

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.