tags:

views:

48

answers:

2

Hi,

I need a PCRE expresssion (regex) to match and replace a certain attribute and value related to a markup element, something like this :

<div style="width:200px;"></div>

into

<div style="width:100px;"></div>

What I have now, parsed by simplehtmldom is the style content in plain text, like this :

width:200px;

How can I match the CSS attribute and replace it with the new values in PHP?

Cheers!

A: 
preg_replace('~width:200px~', 'width:100px', $subject);
Sjoerd
that only works if the attribute and value are expected to be like that.
yoda
+2  A: 
([^\s:]+)[\s:]+([^:;]+)

will extract the values around the colon into backreferences 1 and 2.

([^\s:]+)[\s:]+(\d+)(\w+)

will do the same but extract the value (200) and the unit (px) separately.

if (preg_match('/([^\s:]+)[\s:]+(\d+)(\w+/', $subject, $regs)) {
    $attribute = $regs[1];
    $value = $regs[2];
    $unit = $regs[3];
} else {
    // no match
}
Tim Pietzcker
+1 That's a nice solution, but it can't cope with a space after the colon, which is quite common. This should sort it: `/([^\s:]+)[\s:]*(\d+)(\w+)/`
Mike
Thanks - I have edited my answer. I used `[ \t]` instead of `\s` to be a bit more explicit - or could there even be newlines there?
Tim Pietzcker
Good question. I haven't checked the specs, but instead I have just altered some CSS on one of my test pages. Newlines both before and after the colon don't appear to bother Firefox in the slightest, so I think less explicit is the way to go.
Mike
so how would preg_replace works in this case?
yoda
also, this works better : ([^ \t:;]+)[ \t:]+([^:;]+)
yoda
@yoda: Well, what do you want to replace with what?
Tim Pietzcker
nevermind, I found better to just separate attributes and respective values into arrays and reorganize the css string, no need for regex replacement :)
yoda