What are the advantages of using a library like htmlpurifier for filtering user input compared to manual methods like htmlentities and nl2br?

When filtering user input in PHP, using a library like htmlpurifier is advantageous compared to manual methods like htmlentities and nl2br because htmlpurifier is specifically designed to clean and sanitize HTML input, ensuring that only safe and valid HTML is allowed. This helps prevent cross-site scripting (XSS) attacks and other security vulnerabilities. Additionally, htmlpurifier offers more advanced customization options and is regularly updated to address new security threats.

// Using htmlpurifier to filter user input
require_once 'path/to/htmlpurifier/library/HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);

$dirty_html = "<script>alert('XSS attack!')</script>";
$clean_html = $purifier->purify($dirty_html);

echo $clean_html;