【问题标题】:How to delete empty tags using PHP "new DomDocument ()"? [duplicate]如何使用 PHP“new DomDocument()”删除空标签? [复制]
【发布时间】:2020-10-07 17:32:00
【问题描述】:

我正在使用 PHP“new DomDocument()”。我想从指定的效果中删除内容为空的标签。但是下面的代码不起作用。我该怎么做?

$html = '<blockquote>
<p>Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s,</p>
</blockquote>
<p>8</p>
<hr>
<p></p>
<strong></strong>
<a href="" title="Link Name" target="_blank"></a>
<img src="tex.png" />
<span></span>
<ul><li></li></ul>
<ol><li></li></ol>
<em></em>
<u></u>
<s></s>
<blockquote></blockquote>
<p>&nbsp;</p>';


$dom = new DomDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

// Selects tags to be processed.
$tags_list = $xpath->query("//p|//br|//a|//strong|//img|//ul|//ol|//li|//em|//u|//s|//hr|//blockquote");

foreach($tags_list as $tag) {

   // Checks and deletes tags with empty content.
   if(  in_array($tag->tagName, ['p','a','strong','blockquote']) ){
        if( $tag->nodeValue == "" ){
            $tag->parentNode->removeChild($tag);
        }
    }   
        
}

$cleanHtml = $dom->saveHTML();
echo $cleanHtml;

期望的结果:

<blockquote>
<p>Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s,</p>
</blockquote>
<p>8</p>
<hr />

我对我的代码进行了编辑。现在运行顺利。但我正在尝试删除&lt;html&gt;&lt;body&gt; 标签。

http://sandbox.onlinephpfunctions.com/code/4551454c5f8d7b239844aef3b5757e24c29fb351

【问题讨论】:

  • @Tygo 我想用现在可用的$xpath-&gt;query 查询来做到这一点。
  • 你能编辑你的问题并发布预期的输出吗?
  • @JackFleeting 我对我的代码进行了编辑。现在运行顺利。但我正在尝试删除“”标签。 sandbox.onlinephpfunctions.com/code/…

标签: php domdocument


【解决方案1】:
<?php
error_reporting(0);

$html = "<blockquote>
<p>Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s,</p>
</blockquote>
<p>8</p>
<hr>
<p></p>
<strong></strong>
<a href=\"\" title=\"Link Name\" target=\"_blank\"></a>
<img src=\"tex.png\" />
<span></span>
<ul><li></li></ul>
<ol><li></li></ol>
<em></em>
<u></u>
<s></s>
<blockquote></blockquote>
<p>&nbsp;</p>";



$dom = new DomDocument();
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'),  LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);


foreach($xpath->query('//p|//br|//a|//strong|//img|//ul|//ol|//li|//em|//u|//s|//hr|//blockquote') as $tag) {    
    // Sadece belirtilen etiketlere işlem yapılır.
    if(  in_array($tag->tagName, ['p','br','strong','ul','ol','li','em','u','s','hr','blockquote']) ){
        // Etiketin öznitelikleri varsa işlem devam eder.
        if( $tag->hasAttributes() ){
            // Etiketin tüm öznitelikleri döngüye alınır.
            foreach (iterator_to_array($tag->attributes) as $all_attribute_detail) {
                // Etiketin tüm öznitelikleri siler.
                $tag->removeAttribute($all_attribute_detail->name);
            }
        }
    }


    // Sadece belirtilen "img" etiketine işlem yapılır.
    if( $tag->tagName == 'img'){
        // Etiketin öznitelikleri varsa işlem devam eder.
        if( $tag->hasAttributes() ){
            // Etiketin src özniteliği blob: | data: | //:0 ve boş ise tespit eder ve etiketi siler.
            preg_match('/(^blob:|^data:|^\/\/:0|^$)/', trim($tag->getAttribute('src')), $matches);
            count($matches[0]) ? $tag->parentNode->removeChild($tag) : "";

            // Etiketin tüm öznitelikleri döngüye alınır.
            foreach (iterator_to_array($tag->attributes) as $img_attribute_detail) {
                // İzin verilenler haricindeki tüm öznitelikleri siler.
                if( !in_array($img_attribute_detail->name, ['src','alt']) ){
                    // Etiketin tüm öznitelikleri silinir.
                    $tag->removeAttribute($img_attribute_detail->name);
                }
            }
        }
    }



    // Sadece belirtilen "a" etiketine işlem yapılır.
    if( $tag->tagName == 'a'){
        // Etiketin öznitelikleri varsa işlem devam eder.
        if( $tag->hasAttributes() ){
            // Etiketin src özniteliği blob: | data: | //:0 ve boş ise tespit eder ve etiketi siler.
            empty(trim($tag->getAttribute('href'))) ? $tag->parentNode->removeChild($tag) : "";

            // Etiketin tüm öznitelikleri döngüye alınır.
            foreach (iterator_to_array($tag->attributes) as $a_attribute_detail) {
                // İzin verilenler haricindeki tüm öznitelikleri siler.
                if( !in_array($a_attribute_detail->name, ['href','target','title']) ){
                    // Etiketin tüm öznitelikleri silinir.
                    $tag->removeAttribute($a_attribute_detail->name);
                }
                $tag->setAttribute('rel', 'nofollow noopener');
            }
        }
    }    
}

foreach($xpath->query('//*[not(*) and not(@*) and not(text()[normalize-space()])]') as $tag) {
    if(  !in_array($tag->tagName, ['hr','br']) ){
        $tag->parentNode->removeChild($tag);
    }
}

$cleanHtml = $dom->saveHTML();
$cleanHtml = preg_replace('~<(\w+)[^>]*>(?>[\p{Z}\p{C}]|<br\b[^>]*>|&(?:(?:nb|thin|zwnb|e[nm])sp|zwnj|#xfeff|#xa0|#160|#65279);|(?R))*</\1>~iu',"",$cleanHtml);


$cleanHtml = strip_tags($cleanHtml,'<p><br><a><strong><img><ul><ol><li><em><u><s><hr><blockquote>');

echo $cleanHtml;

?>

【讨论】:

    猜你喜欢
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 2018-09-05
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多