What potential pitfalls should be considered when using the htmlspecialchars function in PHP?

When using the htmlspecialchars function in PHP, it's important to be aware of potential pitfalls such as double escaping, which can lead to unintended characters being displayed. To avoid this, you should use the ENT_QUOTES flag to only escape double quotes, single quotes, ampersands, and less than and greater than signs.

// Using htmlspecialchars with ENT_QUOTES flag to avoid double escaping
$unsafe_string = "<script>alert('XSS attack');</script>";
$safe_string = htmlspecialchars($unsafe_string, ENT_QUOTES);
echo $safe_string;