是否有一种方法可以从字符串中删除除 php 中的父标签之外的所有嵌套 html 标签?
例子:
输入:
This <pre>is a <b>pen</b> and I like <i>it!</i></pre> Good <a>morning <pre>Mary</pre>!</a> Bye.
输出:
This <pre>is a pen and I like it!</pre> Good <a>morning Mary!</a> Bye.
最佳答案
我编写了一个可能适合您的简单代码,我使用了类 DOMDocument 解析 HTML 字符串并获取主要的子节点:
//Your HTML
$html = 'This <pre>is a <b>pen</b> and I like <i>it!</i></pre> Good <a>morning <pre>Mary</pre>!</a> Bye.';
$dom = new DomDocument;
$dom->loadHtml("<body>{$html}</body>");
$nodes = iterator_to_array($dom->getElementsByTagName('body')->item(0)->childNodes);
$nodesFinal = implode(
array_map(function($node) {
if ($node->nodeName === '#text') {
return $node->textContent;
}
return sprintf('<%1$s>%2$s</%1$s>', $node->nodeName, $node->textContent);
}, $nodes)
);
echo $nodesFinal;
告诉我:
This <pre>is a pen and I like it!</pre> Good <a>morning Mary!</a> Bye.
编辑
在接下来的代码中,我得到了获取标签中的属性和 html 字符串中的 UTF8 编码的解决方案:
//Your HTML
$html = '<a href="https://sample.com" target="_blank">Test simple <span>hyperlink.</span></a> This is a text. <div class="info class2">Simple div. <b>A value bold!</b>.</div> End with a some váúlé...';
$dom = new DomDocument;
$dom->loadHtml("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/><body>{$html}</body>");
$nodes = iterator_to_array($dom->getElementsByTagName('body')->item(0)->childNodes);
$nodesFinal = implode(
array_map(function($node) {
$textContent = $node->nodeValue;
if ($node->nodeName === '#text') {
return $textContent;
}
$attr = implode(' ', array_map(function($attr) {
return sprintf('%s="%s"', $attr->name, $attr->value);
}, iterator_to_array($node->attributes)));
return sprintf('<%1$s %3$s>%2$s</%1$s>', $node->nodeName, $textContent, $attr);
}, $nodes)
);
echo $nodesFinal;
告诉我:
<a href="https://sample.com" target="_blank">Test simple hyperlink.</a> This is a text. <div class="info class2">Simple div. A value bold!.</div> End with a some váúlé...
我使用 meta
标签设置对象的编码和名为 attributes
的属性 DOMNode
关于php - 删除php中嵌套的html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47105186/