Using $$vars
and $GLOBALS
both represent security risks. The user should be able to explicitly define the list of tags that are acceptable.
Below is the simplest single-function general solution I could devise. I chose to use double-braces as tag delimiters, but you can modify it easily enough.
/**
* replace_tags replaces tags in the source string with data from the vars map.
* The tags are identified by being wrapped in '{{' and '}}' i.e. '{{tag}}'.
* If a tag value is not present in the tags map, it is replaced with an empty
* string
* @param string $string A string containing 1 or more tags wrapped in '{{}}'
* @param array $tags A map of key-value pairs used to replace tags
* @param force_lower if true, converts matching tags in string via strtolower()
* before checking the tags map.
* @return string The resulting string with all tags replaced.
*/
function replace_tags($string, $tags, $force_lower = false)
{
return preg_replace_callback('/\\{\\{([^{}]+)\}\\}/',
function($matches) use ($tags)
{
$key = $force_lower ? strtolower($matches[1]) : $matches[1];
return array_key_exists($key, $tags)
? $tags[$key]
: '';
}
, $string);
}
[edit] Added force_lower
param