使用PHP从HTML标记中删除属性

时间:2014-05-23 10:32:56

标签: php preg-replace strip-tags

如何删除表格的属性,例如height, border-spacing and style="";

<table style="border-collapse: collapse" border="0" bordercolor="#000000" cellpadding="3" cellspacing="0" height="80" width="95%">

到此 - &gt;

<table>

strip_tags适用于翻录代码,但是preg_replace呢?

仅供参考:从数据库加载东西,它有所有这些奇怪的样式,我想摆脱它们。

1 个答案:

答案 0 :(得分:1)

如果您真的想使用preg_replace,这是可行的方法,但请记住preg_replace不可靠

$output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $html);

我建议你使用为这种操作而存在的php DOM:

// load HTML into a new DOMDocument
$dom = new DOMDocument;
$dom->loadHTML($html);

// Find style attribute with Xpath
$xpath = new DOMXPath($dom);
$styleNodes = $xpath->query('//*[@style]');

// Iterate over nodes and remove style attributes
foreach ($styleNodes as $styleNode) {
  $styleNode->removeAttribute('style');
}

// Save the clean HTML into $output
$output = $dom->saveHTML();
相关问题