How can the use of preg_replace_callback improve the security and reliability of replacing constants in PHP templates?

When replacing constants in PHP templates, using preg_replace_callback can improve security and reliability by allowing for more control over the replacement process. This function allows you to define a callback function that will be executed for each match found, giving you the ability to validate, sanitize, or manipulate the replacement value before it is inserted into the template. This can help prevent injection attacks, ensure the correctness of the replacement, and make the code more maintainable.

// Example of using preg_replace_callback to replace constants in a PHP template
$template = 'Hello, {NAME}! Your account balance is {BALANCE}.';
$constants = ['NAME' => 'John', 'BALANCE' => '$100'];

$result = preg_replace_callback('/\{([A-Z]+)\}/', function($matches) use ($constants) {
    $constant = $matches[1];
    return isset($constants[$constant]) ? $constants[$constant] : '';
}, $template);

echo $result;