How can child nodes within a specific HTML tag be copied, the tag removed, and the child nodes reinserted in PHP?

To copy child nodes within a specific HTML tag, remove the tag, and reinsert the child nodes in PHP, you can use the DOMDocument class to parse the HTML and manipulate the DOM structure. First, identify the target tag and its child nodes. Then, extract the child nodes, remove the target tag, and reinsert the child nodes in the desired location.

$html = '<div><p>Hello</p><p>World</p></div>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$targetTag = $dom->getElementsByTagName('div')->item(0);
$childNodes = [];

foreach ($targetTag->childNodes as $child) {
    $childNodes[] = $child;
}

foreach ($childNodes as $child) {
    $targetTag->parentNode->insertBefore($child, $targetTag);
}

$targetTag->parentNode->removeChild($targetTag);

echo $dom->saveHTML();