How can the DOM be utilized in PHP for manipulating HTML content within a string?

To manipulate HTML content within a string in PHP, the DOMDocument class can be utilized to parse the HTML string and then manipulate its elements using DOM methods. By loading the HTML string into a DOMDocument object, you can easily traverse the DOM tree, modify elements, add new elements, or extract specific content.

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

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

// Manipulate the HTML content
$paragraph = $dom->getElementsByTagName('p')[0];
$paragraph->nodeValue = 'Hello, PHP!';

// Get the modified HTML string
$modifiedHtml = $dom->saveHTML();

echo $modifiedHtml;