Replacing Placeholder Variables in a String
I think for such a simple task you don't need to use RegEx:
$variables = array("first_name"=>"John","last_name"=>"Smith","status"=>"won");
$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.';
foreach($variables as $key => $value){
$string = str_replace('{'.strtoupper($key).'}', $value, $string);
}
echo $string; // Dear John Smith, we wanted to tell you that you won the competition.
I hope I'm not too late to join the party — here is how I would do it:
function template_substitution($template, $data)
{
$placeholders = array_map(function ($placeholder) {
return strtoupper("{{$placeholder}}");
}, array_keys($data));
return strtr($template, array_combine($placeholders, $data));
}
$variables = array(
'first_name' => 'John',
'last_name' => 'Smith',
'status' => 'won',
);
$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you have {STATUS} the competition.';
echo template_substitution($string, $variables);
And, if by any chance you could make your $variables
keys to match your placeholders exactly, the solution becomes ridiculously simple:
$variables = array(
'{FIRST_NAME}' => 'John',
'{LAST_NAME}' => 'Smith',
'{STATUS}' => 'won',
);
$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you have {STATUS} the competition.';
echo strtr($string, $variables);
(See strtr() in PHP manual.)
Taking in account the nature of the PHP language, I believe that this approach should yield the best performance from all listed in this thread.
EDIT: After revisiting this answer 7 years later, I noticed a potentially dangerous oversight on my side, which was also pointed out by another user. Be sure to give them a pat on the back in the form of an upvote!
If you are interested in what this answer looked like before this edit, check out the revision history