2011-02-10 11 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) –

+7

'style =" red "'は大きなナンセンスです。サンプルコードを整理してください。 – ThiefMaster

+1

@Linus [それは間違っているのでその質問にリンクしてはいけません](http://stackoverflow.com/questions/4231382/regular-expression-pattern-not-matching-anywhere-in-string/4234491#4234491) – Gordon

答えて

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: redまたはbackground-color: red、...変化を意味:

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

に...

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

追加の 'style'値の前に'; 'を置くべきです。 – Gumbo

+0

@ Gumbo:私の編集では、コピーや貼り付けの代わりにカット/ペーストが修正されました。ありがとう。 – netcoder

1

OKなので、これはパーサに適しだろうが、あなたは、属性の順序を保証することができれば、これは動作する可能性...

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

私はしなかったものを除外感覚として、ThiefMasterがコメントで言ったように。正規表現(すなわち:適切な方法)を使用せず

関連する問題