【问题标题】:Removing attributes from HTML Tags with PHP使用 PHP 从 HTML 标签中删除属性
【发布时间】:2014-05-23 10:32:56
【问题描述】:

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

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

到这里 -->

<table>

strip_tags 用于撕掉标签,但是preg_replace 呢?

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

【问题讨论】:

标签: php preg-replace strip-tags


【解决方案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();

【讨论】:

    猜你喜欢
    • 2012-02-17
    • 2015-06-16
    • 1970-01-01
    • 2010-10-20
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2019-11-29
    相关资源
    最近更新 更多