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
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.
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 groupBut 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:
See this regex101 demo for a fuller explanation and example matches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With