2

I know people often get told off here for using regexes to fiddle with HTML which I understand but I think in this case I have a valid use for it to alter a CSS file. Unfortunately I am hopeless at writing them myself.

I'm writing a script (PHP) that needs to dynamically add/remove items in a CSS file. As an example the CSS file may have the following declaration:

.cat-item-4 {
    background: #ff0fcd;
}

Presumably a regex is possible to remove this whole declaration? It may contain other things asides from "background" so would need to spot the .cat-item-4 class and then remove both that and everything between and including the parentheses. The whole lot basically.

Any help appreciated.

3
  • CSS != HTML... Using Regexes for this isn't so bad... but I wonder if you really need to do it in the first place. Commented Feb 17, 2012 at 23:23
  • 1
    Yea I realise they're different, I was just trying to avoid the usual wrath that ensues when asking about regexes here! The situation is a bit complex and probably not worth fully explaining, essentially it's for a wordpress plugin that will allow me to assign a hex colour to a category via the admin so the plugin needs to control the display of these classes. I could do it with ugly inline CSS but I'm trying to keep this as neat as possible! Commented Feb 17, 2012 at 23:28
  • No problem. As long as you aren't changing it "on the fly" frequently, it's not a big deal,AFAIC Commented Feb 17, 2012 at 23:31

1 Answer 1

1

You can use a regex find/replace with:

$re = "#\.\bcat-item-4\b.+?\}#s";

Coupled with the modifier PCRE_DOTALL (s), this will find all classes with the name bcat-item-4. The # signs tell PHP what delimiter to use, because after the second #, the 's' indicates that the . should match newlines, which is essential in removing the entire declaration.

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

2 Comments

You would have to be careful there are no } inside the rule, for example as part of a url for a background image.
this works a treat, thanks a lot. the usage will all be very simple, nothing beyond a background hex number or a color hex, nothing fancy so no stress. thanks again.

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.