PHP regex templating – find all occurrences of {{var}}

Use preg_replace_callback(). It’s incredibly useful for this kind of thing.

$replace_values = array(
  'test' => 'test two',
$result = preg_replace_callback('!\{\{(\w+)\}\}!', 'replace_value', $input);

function replace_value($matches) {
  global $replace_values;
  return $replace_values[$matches[1]];

Basically this says find all occurrences of {{…}} containing word characters and replace that value with the value from a lookup table (being the global $replace_values).

Leave a Comment