Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a CSS class name

Tags:

regex

css

php

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.

like image 476
Abs Avatar asked Jun 13 '11 10:06

Abs


People also ask

Can you do regex in CSS?

You can use regular expressions (regex) and cascading style sheet (CSS) selectors as operators wherever trigger filters are used. When a regular expression or CSS selector is set as the operator for a trigger, you can specify that the trigger matches the rule.

What is regex CPP?

Regular Expression or regexes or regexp as they are commonly called are used to represent a particular pattern of string or text. Regexes are often used to denote a standard textual syntax of a string. => Visit Here To See The C++ Training Series For All.


1 Answers

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.

like image 128
Peter Avatar answered Sep 28 '22 08:09

Peter