Reputation: 1668
I'm trying to take classes from a css file using regex. I need to take classes between start and end of match string because most of the class are starting with the same prefix like myy-
classname followed by its rules so i'm giving the {
as end point, because i need to take only the class name.
For Example
.myy-foobar{
/*CSS Rules goes here*/
}
.myy-anotherbar{
/*CSS Rules goes here*/
}
Now i need to take foobar,anotherbar using regex, so i used this preg_match_all
preg_match_all('/^myy-[(.*)]{$/', $file, $match);
var_dump($match);
To my understanding it should start with myy- so i put ^myy-
and any character between this so i used []
and end with { so i used {$
and this
preg_match_all('/(myy-)(.*)({)/', $file, $match);
var_dump($match);
Here too same logic(start with myy- and any character and end with {) i tried with different syntax but nothing helps.
There are lot of classes in the file so i need to take only the middle part of all class as i know the prefix already.
Can anyone help on this?
Upvotes: 1
Views: 2360
Reputation: 41838
To match just the name, use \.myy-\K[^{\s]+(?=\s*{)
$regex = '~\.myy-\K[^{\s]+(?=\s*{)~';
preg_match_all($regex, $yourstring, $matches);
print_r($matches[0]);
See the matches in the Regex Demo.
Explanation
\.myy-
matches .myy-
\K
tells the engine to drop what was matched so far from the final match it returns[^{\s]+
matches any chars that are not a {
or a white-space char (this is the match)(?=\s*{)
asserts that what follows is optional whitespace chars and a {
To match the whole class use this: \.myy-.*?}
$regex = '~\.myy-.*?}s~';
preg_match_all($regex, $yourstring, $matches);
print_r($matches[0]);
Longest Match. The greedy .*
first matches the whole string, then backtracks only as far as needed to allow the next token to match. Therefore, you will often overshoot the place where you want the match to end (longest match).
Shortest Match. The lazy .*?
(made "lazy" by the ?
) means that the dot only matches as many characters as needed to allow the next token to match (shortest match).
Reference
Upvotes: 3
Reputation: 174696
The below code would match the text after .myy-
upto the next {
symbol ,
preg_match_all('~\.myy-\K[^{]*(?={)~', $file, $match);
var_dump($match);
OR
The below code would match the text after .myy-
upto the next {
symbol or :
symbol.
preg_match_all('~\.myy-\K[^{:]*(?={|:)~', $file, $match);
var_dump($match);
Explanation:
\.myy-
Matches the string .myy-
\K
discards the previously matched characters.[^{]*
Matches any charcter not of {
zero or more times.(?={)
Only when the following charcter must be a {
open curly brace.(?=)
is called positive look-aheadUpvotes: 1