What is the best way to recursively search through a DOMDocument in PHP to find and remove specific nodes?

When recursively searching through a DOMDocument in PHP to find and remove specific nodes, you can use a recursive function that traverses the DOM tree and checks each node for the desired criteria. If a node matches the criteria, it can be removed using the `removeChild()` method. This approach ensures that all nested nodes are also searched and removed if necessary.

function removeNodesByTagName(DOMNode $node, string $tagName) {
    $children = $node->childNodes;
    
    for ($i = $children->length - 1; $i >= 0; $i--) {
        $child = $children->item($i);
        
        if ($child->nodeType === XML_ELEMENT_NODE && $child->tagName === $tagName) {
            $node->removeChild($child);
        } else {
            removeNodesByTagName($child, $tagName);
        }
    }
}

// Example usage
$doc = new DOMDocument();
$doc->loadHTML($html);

removeNodesByTagName($doc, 'div');

echo $doc->saveHTML();