What are the potential security implications of using regular expressions in PHP to manipulate HTML content?

Using regular expressions in PHP to manipulate HTML content can potentially lead to security vulnerabilities such as allowing for XSS attacks if not properly sanitized. To mitigate this risk, it is important to use a secure method for manipulating HTML content, such as using PHP's built-in DOMDocument class to parse and manipulate HTML.

// Example of using DOMDocument to manipulate HTML content securely
$html = '<div><p>Hello, World!</p></div>';

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

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

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