2

I can't find a correct regular expression to extract classes names. It is my code:

preg_match_all('@\.(.*!\.){display:none}@', '.UlEa{display:none}.RNLW{display:inline}.jc0k{display:none}.Lyhf{display:inline}', $matches);

The $matches is empty. How should look correct regular expression?

2
  • 1
    Try '@\.(\w+){display:none}@'. Why did you use !? Commented Sep 28, 2016 at 8:05
  • Thx, it works. When I didn't used ! function returns me 1 result: UlEa{display:none}.RNLW{display:inline}.jc0k{display:none}.Lyhf Commented Sep 28, 2016 at 8:11

1 Answer 1

2

Note that your regex matches a literal ., then captures a sequence of any 0+ chars other than linebreak symbols as many as possible up to the last !. sequence and then matches {display:none}. Since your text does not contain ! nor the next . you have no match.

One way to get your matches is to use \w+ (=one or more word characters, those in the [a-zA-Z0-9_] set) pattern inside Group 1:

\.(\w+){display:none}

See the regex demo

PHP demo:

preg_match_all('@\.(\w+){display:none}@', '.UlEa{display:none}.RNLW{display:inline}.jc0k{display:none}.Lyhf{display:inline}', $matches);
print_r($matches[1]); // => Array ( [0] => UlEa [1] => jc0k  )
Sign up to request clarification or add additional context in comments.

9 Comments

However it's not OP's requirement, may you add a version to capture all class names / ids before a CSS body? +1
@revo: Once you provide test cases for that, sure. Also, try '@\.([^{.]+){display:none}@'.
Here you are. To capture all ids / class names before a CSS block declaration.
@revo: There is only one CSS block that has {display:none} and it matches correctly. That means it is already a different question that you may ask as a separate one. Also, you have not mentioned what exact values you need to extract from that string.
Whatever CSS block contains is not important. Just all ids and class names before each single block. Like id-name as an id, class-name and jc0k as class-names for the first block and id-name-two as an id for the second one. I saw the title of this question very relevant so I thought it could be great if you expand the scope of the answer to cover most possible cases (for future reference) that not only extracts class-names but also ids.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.