Ok so I'm trying to do something like so:
preg_replace("/\{([a-zA-Z0-9_]+)\}/", $templateVariables[$1], $templateString);
Now I know that is not possible like it is, however I would like to know if there is a way to do this, because I have tried to use create_function however, $templateVariables is a local variable to the function that it is within, so I can't access $templateVariables from within create_function, so I'm kind of stuck here. I would rather not have to find the matches figure out what to replace them with and then find them again to replace, that just seems horrible inefficient. So is there anyway I can get to a local variable from within an anonymous function or does anyone have any good suggestions.
Thanks.
Try this:
$vars = array(
"test" => "Merry Christmas",
);
$string = "test {test} test";
$string = preg_replace_callback("/\{([a-zA-Z0-9_]+)\}/", function($match) use ($vars) {
return isset($vars[$match[1]]) ? $vars[$match[1]] : $match[0];
}, $string);
echo $string;
It should output:
test Merry Christmas test
You can see a working example here http://codepad.viper-7.com/2ZNNYZ