【问题标题】:Remove nested html tags in php去除 php 中嵌套的 html 标签
【发布时间】:2017-11-03 22:22:32
【问题描述】:

有没有一种方法可以从一个字符串中删除所有嵌套的html标签,除了php中的父标签?

例子:

输入:

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

输出:

是一支笔,我喜欢它!
早安玛丽!再见。

【问题讨论】:

    标签: php html nested tags


    【解决方案1】:

    我编写了一个可能对你有用的简单代码,我使用了 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标签来设置对象DOMNode的编码和名为attributes的属性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多