How can DomDocument be utilized as an alternative to regex for manipulating HTML content in PHP applications?

When manipulating HTML content in PHP applications, using DomDocument instead of regex can provide a more reliable and structured approach. DomDocument allows for parsing, modifying, and generating HTML content using the Document Object Model (DOM), which is specifically designed for working with structured documents like HTML. This can help avoid common pitfalls and errors that can occur when using regex to manipulate HTML.

// Example of using DomDocument to manipulate HTML content
$html = '<div><p>Hello, <strong>world</strong>!</p></div>';

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

// Modify the HTML content
$paragraph = $dom->getElementsByTagName('p')->item(0);
$paragraph->setAttribute('class', 'greeting');

// Output the modified HTML content
echo $dom->saveHTML();