What potential issues or pitfalls should be considered when using htmlspecialchars_decode in PHP?

When using htmlspecialchars_decode in PHP, it is important to be cautious of potential security vulnerabilities such as cross-site scripting (XSS) attacks. This function can decode HTML entities, which could potentially reintroduce malicious scripts into the output if not used carefully. To mitigate this risk, it is recommended to sanitize user input before applying htmlspecialchars_decode.

// Sanitize user input before using htmlspecialchars_decode
$userInput = "<script>alert('XSS attack!');</script>";
$sanitizedInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Decode HTML entities safely
$decodedInput = htmlspecialchars_decode($sanitizedInput);

echo $decodedInput;