0

I'm working on this RegEx to match and replace CSS with other CSS values. So far I have this:

$css_new = preg_replace('/('.$definition.'.*?\s'.$property.':)[^;]*([^}]*)/is','$1 '.$value.'$2',$css_temp);

The issue I have is that if I am trying to replace something in the definition ".menu" values also get replaced in the ".menu li" definition.

I was thinking of adding a "{" somewhere but I'm not having luck with it. I tried this:

$css_new = preg_replace('/('.$definition.'{.*?\s'.$property.':)[^;]*([^}]*)/is','$1 '.$value.'$2',$css_temp);

Thanks for your help.

2 Answers 2

1

I assume $definition always contains the entire selector. (And note that you replace the dot in your definition before adding it to your regexp, else .menu would match smenu as well)

$definition = '.submenu';

// no match:
.menu .submenu

I also assume that the CSS is not entirely clean (so double spaces can occur etc.).

.menu    .submenu {

Next assumption is that multiple (comma) separated CSS rules do NOT exist (else you would be changing more than 1 rule):

.menu .submenu, .menu .list {

Then this should work: (not fully tested)

$cleanDefinition = str_replace(array('.', ' '), array('\.', '\s+'), $definition);
$result = preg_replace('/((?:}|^)\s*'.$cleanDefinition.'\s*{.*'.$property.'\s*:)(.+?)(;.*?})/is', '$1'.$value.'$3', $css_temp);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for your help! All assumptions but the last one are correct. Can this code be changed to also change properties of multiple comm-.separated definitions?
0

Just wanted to report how I solved this problem. I was able to come up with this line and have tested it extensively.

$css_new = preg_replace('/(.*^'.$definition.'\s{.*?\s'.$property.':)[^;]*([^}]*)/ism','$1 '.$value.'$2',$css_temp);

If you see something wrong with this line please let me know but I believe this solves the issue.

Comments

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.