- htmlspecialchars: documentation ( source)
<?php
$str = <<<HTML
<!doctype html>
<html>
<body>
text to keep <span xxx="xxxx"><span xxx="xxx">unwanted text</span> unwanted text </span> text to keep
</body>
</html>
HTML;
$doc = new DOMDocument();
$doc->loadHTML($str);
$xpath = new DOMXPath($doc);
foreach($xpath->evaluate("//span") as $node) {
echo 'Removing: '.$node->nodeValue."<br>";
$node->parentNode->removeChild($node);
}
$output = $doc->saveHTML();
echo htmlspecialchars($output);