所以,到目前为止我只能保留一个属性,但我试图将 class 和 id 属性保留在 HTML 标签中
代码:
$string = '<div id="one-id" class="someClassName">Some text <a href="#" title="Words" id="linkId" class="classLink">link</a> with only the class and id attrtibutes./div>';
preg_replace("/<([a-z][a-z0-9]*)(?:[^>]*(\sclass=['\"][^'\"]*['\"]))?[^>]*?(\/?)>/i", '<$1$2$3>', $string);
输出:
<div class="someClassName">Some text <a class="classLink">link</a> with only the class and id attrtibutes./div>
我试图从每个标签中删除除 class 和 id 属性之外的所有其他属性。
迭代 dom 中的所有节点,然后反向循环所有属性,以便您可以安全地修剪不在白名单中的属性。
(我修复了示例输入中
</div>
中的拼写错误。)
代码:(演示)
$html = '<div id="one-id" class="someClassName">Some text <a href="#" title="Words" id="linkId" class="classLink">link</a> with only the class and id attrtibutes.</div>';
$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//*') as $node) {
for ($i = $node->attributes->length - 1; $i >= 0; --$i) {
$attr = $node->attributes->item($i);
if (!in_array($attr->name, ['id', 'class'])) {
$node->removeAttribute($attr->name);
}
}
}
echo $dom->saveHTML();
输出:
有些文本链接仅包含类和 ID 属性。