How can PHP developers prevent str_replace from making unintended replacements in nested HTML elements?

When using str_replace in PHP to replace text within HTML elements, it can inadvertently affect nested HTML elements if not used carefully. To prevent unintended replacements within nested elements, developers can use a combination of DOM manipulation functions and regular expressions to target specific elements or attributes for replacement.

// Sample code to prevent unintended replacements in nested HTML elements
$html = '<div class="container"><p>Hello, <span class="name">John</span></p></div>';

// Create a DOMDocument object
$doc = new DOMDocument();
$doc->loadHTML($html);

// Find all elements with class="name" and replace the text within them
$xpath = new DOMXPath($doc);
$elements = $xpath->query('//span[@class="name"]');
foreach ($elements as $element) {
    $element->nodeValue = str_replace('John', 'Jane', $element->nodeValue);
}

// Get the modified HTML content
$modifiedHtml = $doc->saveHTML();
echo $modifiedHtml;