php - 删除php中嵌套的html标签

标签 php html nested tags

是否有一种方法可以从字符串中删除除 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/

相关文章:

javascript - 如何使用 postMessage 从嵌套 iFrame 到根文档进行通信?

python - 扁平化嵌套循环/降低复杂性 - 互补对计数算法

PHP fatal error : Call to undefined function how do I fix it?

php - 搜索逻辑可高效访问 6 个以上相关表

php - 数组更新语句清空 SQL 表中的记录。 - 更新

php - 在 <a > 标记、 anchor 标记内调用 PHP 函数

css - 不同浏览器中的不同行为都没有产生预期的结果

javascript - 无法加载 jQuery 代码

javascript - 关闭灯箱后模态窗口覆盖仍然存在

javascript - 带有嵌套指令的 Angularjs