If you had a string that looked something like this:
Hello! My name is {$name}, I am {$age} years old.
…and you needed to replace all those variables with something dynamic. Here’s how you can do it:
Alternative 1: Pre-defined array
We can pre-define a replacement array of what we want to exchange and what we want to change things into.
$string = 'Hello! My name is {$name}, I am {$age} years old.';
$replacement_array = array(
'name' => 'Bob',
'age' => 22
);
$string_processed = preg_replace_callback(
'~\{\$(.*?)\}~si',
function($match) use ($replacement_array)
{
return str_replace($match[0], isset($replacement_array[$match[1]]) ? $replacement_array[$match[1]] : $match[0], $match[0]);
},
$string);
echo $string_processed;
This script will print:
Hello! My name is Bob, I am 22 years old.
Of course the $replacement_array can contain any values you want, even dynamic ones. But perhaps a pre-defined array is too much work, let’s try another approach:
Alternative 2: Resolve the variables from global space (or whatever scope you happen to be in at the time of execution).
$string = 'Hello! My name is {$name}, I am {$age} years old.';
$name = "Bob";
$age = 22;
$string_processed = preg_replace_callback(
'~\{\$(.*?)\}~si',
function($match) use ($name, $age)
{
return eval('return $' . $match[1] . ';');
},
$string);
echo $string_processed;
No more replacement array! But because we use preg_replace_callback with an anonymous function, we have to declare that we are going to “use” the variables $name and $age inside the callback function.
In effect, this is kind of like a tiny templating engine. :)