2011-02-10 64 views
1

我需要在表格/ td/tr/th标签中更改宽度和高度属性的所有发生的样式。PHP - 正则表达式,用于转换样式中的宽度/高度属性

例如,

<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> 

我该怎么办呢?

+4

[不可使用正则表达式染指(X)HTML] (http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – 2011-02-10 15:13:50

+7

`style =“red”`是主要的废话。请清理你的示例代码。 – ThiefMaster 2011-02-10 15:13:52

回答

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

OK,所以这将是更适合一个分析器,但如果你能保证属性的顺序,这可能工作...

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

我离开了这东西没有做感觉如同ThiefMaster在评论中说。

相关问题