Abs
Abs

Reputation: 57916

Regex to match a CSS class name

I am trying to write a regex that matches a valid CSS class name structure. I have this so far:

$pattern = "([A-Za-z]*\.[A-Za-z]+\s*{)";

$regex = preg_match_all($pattern, $html, $matches);

However, a class name can be in the following formats that my regex won't match:

p.my_class{
}
p.thisclas45{
}

These are just some cases, I've looked around to find the rules of how you can name a class in a style block but couldn't find anything. Anyone know where the rules for the class naming conventions are?

Are there any more cases that I need to consider? What regex would you use to match a class name?

I have already narrowed it down to a style block using the PHP DOM Document class.

Upvotes: 13

Views: 20851

Answers (3)

Raghavan Vidhyasagar
Raghavan Vidhyasagar

Reputation: 493

This regex will select all classes in a CSS file, no matter how much complex the CSS code is.

/(?<=\.)([a-zA-Z0-9_-]+)(?![^\{]*\})/g

Eg:

.class-1:focus > :is(button, a, div) > :first-child > .class2:first-child > .class_3 #id-1 + * { 
    padding: 8.3px;
    -webkit-box-align: center;
    color: #ff4834 !important;
}
@keyframes shimmer {
    0% {
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
    to {
        -webkit-transform: translateX(100%);
        transform: translateX(100%);
    }
}

Output:

['class-1', 'class2', 'class_3']

Upvotes: 2

Paolo Stefan
Paolo Stefan

Reputation: 10253

This regex:

/(\w+)?(\s*>\s*)?(#\w+)?\s*(\.\w+)?\s*{/gm

will match any of the following:

p.my_class{}
p.thisclas45{}
.simple_class{}
tag#id.class{}
tag > #id{}

You can play around with it, on RegExr, here.

Upvotes: 2

Peter
Peter

Reputation: 3956

Have a look at http://www.w3.org/TR/CSS21/grammar.html#scanner

According to this grammar and the post Which characters are valid in CSS class names/selectors? this should be the right pattern to scan for css classes:

\.-?[_a-zA-Z]+[_a-zA-Z0-9-]*\s*\{

Note: Tag names are not required as prefix for classes in css. Just .hello { border: 1; } is also valid.

Upvotes: 25

Related Questions