开发者

PCRE replace markup style

开发者 https://www.devze.com 2023-01-05 03:20 出处:网络
I need a PCRE expresssion (regex) to match and replace a certain attribute and value related to a markup element, something like this :

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消