How can DOMDocument and DOMXPath be utilized to filter specific text in PHP without affecting other elements?

To filter specific text in PHP without affecting other elements, you can use DOMDocument to parse the HTML content and DOMXPath to query for the specific text nodes. By using XPath expressions to target the desired text nodes, you can extract the text without altering the structure of the HTML document.

$html = '<div><p>This is some text</p><p>Another paragraph</p></div>';
$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$textNodes = $xpath->query('//text()');

foreach ($textNodes as $node) {
    if (strpos($node->nodeValue, 'some text') !== false) {
        echo $node->nodeValue . '<br>';
    }
}