How can the DOM approach be utilized in PHP to manipulate and replace specific substrings in HTML content?

To manipulate and replace specific substrings in HTML content using the DOM approach in PHP, you can utilize the DOMDocument class to load the HTML content, then use DOMXPath to query for specific elements or text nodes that you want to replace. Once you have identified the target substrings, you can use DOMDocument methods to modify or replace them accordingly.

<?php
$html = '<div><p>Hello, <span>world</span>!</p></div>';

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

$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//p/span');

foreach ($nodes as $node) {
    $newText = $dom->createTextNode('everyone');
    $node->parentNode->replaceChild($newText, $node);
}

$newHtml = $dom->saveHTML();
echo $newHtml;
?>