What best practices should be followed when replacing template variables with PHP scripts in a PHP application?

When replacing template variables with PHP scripts in a PHP application, it is important to ensure that the code is secure and follows best practices to prevent vulnerabilities such as code injection attacks. One way to do this is by using PHP's htmlspecialchars function to escape any user input that is being output to the page. This helps to prevent malicious scripts from being executed.

<?php
// Example of replacing template variables with PHP scripts
$userInput = "<script>alert('XSS attack!');</script>";
echo "User input: " . htmlspecialchars($userInput);
?>