How can I remove DOM element tags but leave their contents?

后端 未结 3 867
深忆病人
深忆病人 2021-01-19 14:20

I have PHP code which removes all nodes that have at least one attribute. Here is my code:


    

These

3条回答
  •  长情又很酷
    2021-01-19 15:02

    You could use replaceChild() with the text content of that node:

    foreach ($lines_to_be_removed as $line) {
      $line->parentNode->replaceChild($dom->createTextNode($line->textContent),$line);
    }
    
    // 
    //

    These line shall stay

    // Remove this one //

    But keep this

    // and this //

    However, this may prove problematic with your // notation of your xpath selector and recursion.


    Using a more manual approach to copy the child contents of the target nodes into the parent nodes.

    $data = '
    
    1A
    1B
    2C
    2D
    2E
    2F
    3G
    3H
    '; $dom = new DOMDOcument(); $dom->loadHTML($data, LIBXML_HTML_NOIMPLIED); $dom->removeChild($dom->doctype); SomeFunctionName( $dom->documentElement ); $html = $dom->saveHTML(); function SomeFunctionName( $parent ) { $nodesToDelete = array(); if( $parent->hasChildNodes() ) { foreach( $parent->childNodes as $node ) { SomeFunctionName( $node ); if( $node->hasAttributes() and count( $node->attributes ) > 0 ) { foreach( $node->childNodes as $childNode ) { $node->parentNode->insertBefore( clone $childNode, $node ); } $nodesToDelete[] = $node; } } } foreach( $nodesToDelete as $delete) { $delete->parentNode->removeChild( $delete ); } } //
    //
    1A
    // 1B //
    2C
    // 2D //
    2E
    // 2F //
    3G
    // 3H //
    3I
    // 3J //

    If you want to nest the child elements in a new "div" container swap out this porition of code

        foreach( $parent->childNodes as $node )
        {
          SomeFunctionName( $node );
          if( $node->hasAttributes() and count( $node->attributes ) > 0 )
          {
            $newNode = $node->ownerDocument->createElement('div');
            foreach( $node->childNodes as $childNode )
            {
              $newNode->appendChild( clone $childNode );
            }
            $node->parentNode->insertBefore( $newNode, $node );
            $nodesToDelete[] = $node;
          }
        }
    
    // 
    //
    1A
    //
    1B //
    2C
    //
    2D
    //
    2E
    //
    2F //
    3G
    //
    3H
    //
    3I
    //
    3J
    //
    //
    //

提交回复
热议问题