PHP - 用于转换样式中宽度/高度属性的正则表达式

时间:2011-02-10 15:12:27

标签: php regex

我需要在table / td / tr / th标签中更改样式中所有出现的width和height属性。

例如,

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

应该成为

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

我该怎么办?

2 个答案:

答案 0 :(得分:4)

不使用正则表达式(即:正确的方式):

$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);
}

注意: red不是有效的CSS属性。您可能需要color: redbackground-color: red,以下内容将转换为...更改:

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

为...

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

答案 1 :(得分:1)

好的,所以这更适合解析器,但是如果你能保证属性的顺序,这可能有用......

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

我遗漏了那些没有意义的东西,ThiefMaster在评论中说。