What are the best practices for handling user-generated content containing HTML tags in PHP applications?

When handling user-generated content containing HTML tags in PHP applications, it is important to sanitize and validate the input to prevent potential security vulnerabilities such as cross-site scripting (XSS) attacks. One way to achieve this is by using PHP's `htmlspecialchars()` function to escape special characters in the input before displaying it on the webpage. This function will convert characters like `<`, `>`, `&`, and `"` to their respective HTML entities, ensuring that the content is displayed as text rather than interpreted as HTML code.

// Sanitize user-generated content containing HTML tags
$userContent = &quot;&lt;p&gt;This is some &lt;strong&gt;user-generated&lt;/strong&gt; content.&lt;/p&gt;&quot;;
$sanitizedContent = htmlspecialchars($userContent);

echo $sanitizedContent;