PCRE replace markup style
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 开发者_StackOverflow中文版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!
([^\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
}
preg_replace('~width:200px~', 'width:100px', $subject);
精彩评论