What are the considerations for securing against HTML and script injections when formatting strings in PHP?

When formatting strings in PHP, it is important to sanitize user input to prevent HTML and script injections. One common method is to use the htmlspecialchars() function to convert special characters to HTML entities, escaping them and preventing them from being interpreted as code by the browser.

$userInput = "<script>alert('Hello!');</script>";
$cleanInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo $cleanInput;