0

Been more than 6 hours trying to find best PHP regex to match a specific class name + :before pseudo. For example I have css code like this

h1 {
  font-size: 3em;
  line-height: 1.65em;
}

p{line-height: 1.5em; margin: 10px 0;}

.action-admin:before{
   content: "";
   display: block;
   width: 50px;
   height: 50px;
}

.action-user:before{
   content: "";
   display: block;
   width: 20px;
   height: 20px;
}

footer{
   clear: both;
}

so, I want to search all css code that have class name match with '.action-{anyotherwords}:before' and listed them in a php variable (will process this to next action)

so, in simple words - I only want to get these code below from my css above

.action-admin:before{
   content: "";
   display: block;
   width: 50px;
   height: 50px;
}

.action-user:before{
   content: "";
   display: block;
   width: 20px;
   height: 20px;
}

1 Answer 1

1

You can use this regex to find all these blocks:

\.action-[\w-]+:before\s*?\{[^}]+\}

enter image description here

Example:

preg_match_all("/\.action-[\w-]+:before\s*?\{[^}]+\}/", $css, $matches);
$actionCSS = implode("\n\n", $matches[0]);

The CSS code with only the action blocks will then be in $actionCSS.

Sign up to request clarification or add additional context in comments.

6 Comments

RegEx should be \.action-[a-z]+:before\s*\{[^}]+\}. Keep in mind this only allows for lowercase letters after ".action".
@tenub True, I limited myself to the bare minimum for his example code, but yours is better for generic CSS.
Thanks. Could you show me how to allow uppercase, number and another "-" too after ".action-" , I have some class with number, Uppercase and double "-", e.g. "action-super-admin{" , "action-Model-Cat1{" - Many thanks! :)
@Omar I've updated the regex to match everything after action, including dashes and uppercase characters (this will also match invalid CSS).
I would only allow numbers, uppercase characters, underscores, and hyphens (which are the only valid css characters that might appear here). Just change [a-z] to [\w-]. [^:] means anything other than a ":" which could include things like "–" or "÷".
|

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.