如何删除属性html并替换另一个属性


How to remove attributes html and replace an another attributes?

我有一个这样的字符串:

<p>title="abc" </p> <p title="a"><a title="b"></a></p><pre title="c"></pre>

我想将字符串title替换为html标记内的class,并将字符串"title"保留在html标记外。如果你有什么想法,请告诉我。谢谢

如果您想用PHP实现这一点,您应该使用DOMDocument。也许这个SO帖子可以帮助你。

编辑:很抱歉只有链接的答案。下面是一个代码示例:

$html = '<p>title="abc" </p><p title="a"><a title="b"></a></p><pre title="c"></pre>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $dom->getElementsByTagName('*');
foreach ($nodes as $node) {
    if ($node->getAttribute('title')) {
        $node->setAttribute('class', $node->getAttribute('title'));
        $node->removeAttribute('title');
    }
}
$html = $dom->saveHTML();
echo $html;

这个代码会给你:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>title="abc" </p><p class="a"><a class="b"></a></p><pre class="c"></pre></body></html>

如果你不需要的话,你可以移除header+额外的标签(html/body)。此处的联机示例