What are some best practices for substituting variables in a template in PHP?

When substituting variables in a template in PHP, it's important to properly sanitize and escape the variables to prevent any security vulnerabilities such as cross-site scripting (XSS) attacks. One common way to substitute variables in a template is to use PHP's `sprintf()` function, which allows you to format a string with placeholders for variables to be inserted. By using `sprintf()` along with proper escaping functions like `htmlspecialchars()`, you can safely substitute variables in a template.

// Example of substituting variables in a template using sprintf() and htmlspecialchars()

$name = "<script>alert('XSS attack!');</script>"; // Example variable with potential XSS vulnerability

// Sanitize the variable before inserting it into the template
$safe_name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');

// Template with placeholders
$template = "<h1>Hello, %s!</h1>";

// Use sprintf() to substitute the variable into the template
$output = sprintf($template, $safe_name);

// Output the final sanitized template
echo $output;