我想删除用户插入的不支持的html标签(系统定义支持的标签),仅支持示例系统“ div ”标签:
<div><span>Hello</span> <span>World</span></div>
将转换为:
<div>Hello World</div>
这是我的带有简单HTML DOM的代码:
function main()
{
$content = '<div><span>Hello</span> <span>World</span></div>';
$html = str_get_html($content);
$html = htmlParser($html);
}
function htmlParser($html)
{
$supportedTags = ['div'];
foreach ($html->childNodes() as $node) {
// Remove unsupported tags
if (!in_array($node->tag, $supportedTags)) {
$node->parent()->innertext = str_replace($node->outertext, $node->innertext, $node->parent()->innertext);
$node->outertext = '';
}
if ($node->childNodes()) {
htmlParser($node);
}
}
return $html;
}
但是如果包含多个嵌套的不受支持的标签,则会出错,例如:
<div><span>Hello</span> <span>World</span> <span><b>!!</b></span></div>
它将转换为
<div>Hello World <b>!!</b></div>
但预期结果是
<div>Hello World !!</div>
解决方案是什么?我应该继续使用简单HTML DOM还是找到其他解决此问题的方法?
感谢您提前解决了我的问题。
答案 0 :(得分:0)
据我所知,您可以做到这一点。 strip_tags($html, '<div><b>');
答案 1 :(得分:0)
经过一番挣扎,我发现我不应该编辑$ node-> parent(),因为它处于循环中,应该首先加载childNodes。代码应如下所示:
function htmlParser($html)
{
$supportedTags = ['div'];
foreach ($html->childNodes() as $node) {
if ($node->childNodes()) {
htmlParser($node);
}
// Remove unsupported tags
if (!in_array($node->tag, $supportedTags)) {
$node->outertext = $node->innertext;
}
}
return $html;
}