[英]Remove unsupported tags of html (Simple HTML Dom)
我想刪除用戶插入的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還是找到其他方法來解決此問題?
感謝您提前解決我的問題。
據我所知,您可以做到這一點。 strip_tags($html, '<div><b>');
范例 : https : //3v4l.org/p4nLV
參考 : http : //php.net/strip_tags
經過一些努力之后,我發現我不應該編輯$ 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.