开发者

PHP - Regular expression to convert width/height attribute in style

I need to change in styles all occurencies of width and height attributes in table/td/tr/th tags.

For example,

<table width="500" height="235" style="color:#FF0000;">
<tr>
<td width="30" height="25" style="color:#FFFF00;">Hello</td>
<td>Worl开发者_如何学运维d</td>
</tr>
</table>

should become

<table style="color:#FF0000;width:500px;height:235px"> 
<tr>
<td style="color:#FFFF00;width:30px;height:25px">Hello</td>
<td>World</td>
</tr>
</table>

how can I do it ?


Without using regular expression (i.e.: the proper way):

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$nodes = $xpath->query('//*[@width or @height]');

foreach ($nodes as $node) {
    $style = $node->getAttribute('style');
    $width = $node->getAttribute('width');
    $height = $node->getAttribute('height');
    $node->removeAttribute('width');
    $node->removeAttribute('height');

    $style = !empty($style) ? "$style;" : '';
    if (!empty($width)) $style .= "width:{$width}px;";
    if (!empty($height)) $style .= "height:{$height}px;";

    $node->setAttribute('style', $style);
}

Note: red is not a valid CSS attribute. You probably meant color: red or background-color: red, for which the following would convert... change:

$style = !empty($style) ? "$style;" : '';

to...

$style = !empty($style) ? "color: $style;" : '';


OK, so this would be better suited to a parser, but if you can guarantee that order of the attributes, this may work...

preg_replace('/<(table|td|tr|th)\s+width="(\d+?)"\s+height="(\d+?)"/',
             '<$1 style="width: $2; height: $3"',
             $str);

I left out the stuff which didn't make sense, as ThiefMaster said in the comments.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜