Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除php中的嵌套html标记_Php_Html_Nested_Tags - Fatal编程技术网

删除php中的嵌套html标记

删除php中的嵌套html标记,php,html,nested,tags,Php,Html,Nested,Tags,在php中是否有一种方法可以从字符串中删除除父标记以外的所有嵌套html标记 例如: 输入: 这是一支钢笔,我喜欢它 信息技术早上好 玛丽!再见 输出: 这是一支钢笔,我喜欢它!好 早上好,玛丽!再见 我编写了一个简单的代码,可能对您有用,我使用该类解析HTML字符串并获取主要的子节点: <a href="https://sample.com" target="_blank">Test simple hyperlink.</a> This is a text. <d

在php中是否有一种方法可以从字符串中删除除父标记以外的所有嵌套html标记

例如:

输入:

这是一支钢笔,我喜欢它 信息技术早上好 玛丽!再见

输出:

这是一支钢笔,我喜欢它!好 早上好,玛丽!再见


我编写了一个简单的代码,可能对您有用,我使用该类解析HTML字符串并获取主要的子节点:

<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é... 
//您的HTML
$html='这是一支钢笔,我喜欢它!好,这是一篇课文。简单分区A值加粗!。以一些vúlé结尾…';
$dom=新的DomDocument;
$dom->loadHtml(“{$html}”);
$nodes=iterator_to_数组($dom->getElementsByTagName('body')->item(0)->childNodes);
$nodesFinal=内爆(
数组映射(函数($node){
$textContent=$node->nodeValue;
如果($node->nodeName=='#text'){
返回$textContent;
}
$attr=内爆(“”,数组映射(函数($attr){
返回sprintf(“%s=”%s“,$attr->name,$attr->value);
},迭代器_to_数组($node->attributes));
返回sprintf(“%2$s”,$node->nodeName,$textContent,$attr);
},$nodes)
);
echo$nodesFinal;
让我看看:

这是一个文本。简单分区A值加粗!。以一些váúlé结尾。。。
我使用
meta
标记设置对象的编码和名为
attributes
的属性

This <pre>is a pen and I like it!</pre> Good <a>morning Mary!</a> Bye.
//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é...