Reputation: 1915
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.
Upvotes: 0
Views: 101
Reputation: 34596
You don't show us what $input_values
contains, but I assume this is a global list of all possible tags to be replaced.
This being the case, one obvious weakness is that you loop over this for each template. If a template happened to have only one tag in it, this is wasteful.
I would be tempted to try changing it up so that, rather than loop over all possible tags for each template, you act only on the tags mentioned in the template, via preg_replace_callback
. I can't guarantee this will be faster, but it would be my first thing to try.
Here's a simplified example:
$transformations = array(
'name' => 'John',
'pronoun' => 'you'
'animal' => 'dog'
'building' => 'house'
'food' => 'chocolate'
'friend' => 'Kelvin'
/* etc, potentially many more */
);
$template = "hello, {name}, how are {pronoun}?";
$transformed_template = preg_replace_callback('/\{(\w*)\}/', function($match) {
global $transformations;
if (isset($transformations[$match[1]]))
return trim($transformations[$match[1]]);
}, $template);
The template contains only two placeholders, and we act only on those, rather than looping through all the possible tag replacements in $transformations
.
(Note I use an anonymous function as the callback to preg_replace_callback()
. If you're on PHP < 5.3 you'll need a named function instead.)
Upvotes: 1