I have a table which contains a set of templates. These templates have placeholders which need to be replaced at runtime given a key,value pair array. Here's my code for making the replacements:
function replace_placeholders(&$input_values) {
$result = execute_pdo_query("SELECT name,value FROM templates");
foreach($result as $currow) {
$varname = $currow[name];
$varvalue = $currow['value'];
foreach($input_values as $key => $value) {
$key = '{'.strtolower($key).'}';
$varvalue = str_replace($key,trim($value),$varvalue);
}
$input_values[$varname] = $varvalue;
}
}
The issue is that there are a large number of templates and many key,value pairs. So, this nested loop gets executed many many times taking up almost half a second. Is there a way to optimize this replacement? I have searched for an optimization but it's mostly said that str_replace is the best that can be done.