从所有 HTML 标签中删除所有不在白名单中的属性

问题描述 投票:0回答:1

所以,到目前为止我只能保留一个属性,但我试图将 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 属性之外的所有其他属性。

php html attributes domdocument sanitization
1个回答
0
投票

迭代 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();

输出:

<div id="one-id" class="someClassName">Some text <a id="linkId" class="classLink">link</a> with only the class and id  attrtibutes.</div>

...实际上,XPath 并不是真正需要的,因为我们正在迭代 dom 中的每个节点。 (演示)

$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ($dom->getElementsByTagName('*') 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();
© www.soinside.com 2019 - 2024. All rights reserved.