2014-02-16 45 views
0

是否有一种简单的方法可以使用PHP从表格中删除内联样式和属性。使用PHP删除表格内联样式

例如,从下面的代码删除类,风格,宽度,高度:

<tr class=xl96 height=30 style='mso-height-source:userset;height:23.1pt'> 
<td height=30 class=xl99 style='height:23.1pt;border-top:none'>9</td> 
<td class=xl100 style='border-top:none;border-left:none'>46333</td> 
<td class=xl101 style='border-top:none;border-left:none'>&yen;698</td> 
<td class=xl99 style='border-top:none;border-left:none'>48</td> 
<td class=xl100 style='border-top:none;border-left:none'>2077988</td> 
<td class=xl101 style='border-top:none;border-left:none'>&yen;698</td> 
<td class=xl98></td> 
<td class=xl96></td> 
<td class=xl96></td> 
</tr> 

预期结果:

<tr> 
<td>9</td> 
<td>46333</td> 
<td>&yen;698</td> 
<td>48</td> 
<td>2077988</td> 
<td>&yen;698</td> 
<td></td> 
<td></td> 
<td></td> 
</tr> 
+0

你可以把HTML的字符串,通过解析,或者你附加一些JavaScript,做的是为你。或者你定义新的CSS与!重要的属性来覆盖内联样式 –

+0

请解释更好 - 你如何得到这个HTML,从哪里? (你的代码打印出来,你正在解析一些页面等等)? – sinisake

+2

为什么不只是通过CSS呢? –

回答

5
$doc = new DOMDocument(); 
$doc->loadHTML($html); 

foreach($doc->getElementsByTagName('*') as $node) 
{ 
    $node->removeAttribute('height'); 
    $node->removeAttribute('style'); 
    $node->removeAttribute('class'); 
} 

$doc->removeChild($doc->firstChild); 
$doc->replaceChild($doc->firstChild->firstChild->firstChild, $doc->firstChild); 

echo $doc->saveHTML(); 

输出

<tr><td>9</td> <td>46333</td> <td>&yen;698</td> <td>48</td> <td>2077988</td> 
<td>&yen;698</td> <td></td> <td></td> <td></td> </tr> 
+0

谢谢,作品不错。 – jlee

+0

+1使用DOM而不是求助于正则表达式。 –

+0

@AmalMurali谢谢.....! –

0
$yourVariable= preg_replace('#(<[a-z ]*)(style=("|\')(.*?)("|\'))([a-z ]*>)#', '\\1\\6', $yourVariable); 

尝试

0

我也只有这样,想象一下,这将工作是这样的:

<?php 
    $styles = ' style="border-top:none;border-left:none;"'; 

    echo '<tr class=xl96 height=30 style='mso-height-source:userset;height:23.1pt'> 
       <td height=30 class=xl99 style='height:23.1pt;border-top:none'>9</td> 
       <td class=xl100'.$style.'>46333</td> 
       <td class=xl101'.$style.'>&yen;698</td> 
       <td class=xl99'.$style.'>48</td> 
       <td class=xl100'.$style.'>2077988</td> 
       <td class=xl101'.$style.'>&yen;698</td> 
       <td class=xl98></td> 
       <td class=xl96></td> 
       <td class=xl96></td> 
      </tr> 


?> 

或使用正则表达式。

0

或者你把这段你的CSS:

Table 
{ 
    border-top:auto !important; 
    border-left:auto !important; 
    Height:auto !important; 
}