Strip HTML tags and its contents

后端 未结 2 654
忘掉有多难
忘掉有多难 2020-12-03 10:58

I\'m using DOM to parse string. I need function that strips span tags and its contents. For example, if I have:

This is some text that contains photo.


        
相关标签:
2条回答
  • 2020-12-03 11:43

    @ile - I've had that problem - it's because the index of the foreach iterator happily keeps incrementing, while calling removeChild() on the DOM also seems to remove the nodes from the DomNodeList ($spans). So for every span you remove, the nodelist shrinks one element and then gets its foreach counter incremented by one. Net result: it skips one span.

    I'm sure there is a more elegant way, but this is how I did it - I moved the references from the DomNodeList to a second array, where they would not be removed by the removeChild() operation.

        foreach($spans as $span) {
            $nodes[] = $span;
        }
        foreach($nodes as $span) {
            $span->parentNode->removeChild($span);
        }
    
    0 讨论(0)
  • 2020-12-03 11:55

    Try removing the spans directly from the DOM tree.

    $dom = new DOMDocument();
    $dom->loadHTML($string);
    $dom->preserveWhiteSpace = false;
    
    $elements = $dom->getElementsByTagName('span');
    while($span = $elements->item(0)) {       
       $span->parentNode->removeChild($span);
    }
    
    echo $dom->saveHTML();
    
    0 讨论(0)
提交回复
热议问题