Regex to match a CSS class name
source link: https://www.codesd.com/item/regex-to-match-a-css-class-name.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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.
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.
Related Articles
Regex is the css class name of a single string containing multiple classes
Type each css class name declared in braces using regex
A tape string for a secure CSS class name?
Does the length of the CSS class name affect browser performance?
Is there a way to make HTML code independent of changes in CSS class names?
Regex to match everything except the name and extension of the image
Why does Visual Studio not resolve my CSS class names?
Process blank spaces in CSS class names with Jsoup
Extend PHP Markdown to accept CSS class names
How to get a CSS class name using Selenium?
Getting div content by css class name
Regular expression for CSS class names
Effect of applying the non-existent CSS class name
Dynamic CSS class names in GWT
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK