Hi I'm writing something for handling my views an I need a preg_replace here, but i can't seem to get it working so I've scrapped the code.
the strings I am trying to replace are dynamic based on a template, e.g.
{{name}} is {{age}} years old
And the passed information into the function is an array e.g.
array( 'name' => 'John Doe', 'age' => '27' );
The pattern I have so far is \{{([a-zA-Z0-9]+)\}}
however this only seems to match one pair of braces.
I'm also having a problem looping through results in preg_match_all..
Thanks in advance
preg_replace_callback
seems like a good candidate.
$str = "{{name}} is {{age}} years old";
$values = array( 'name' => 'John Doe', 'age' => '27' );
echo preg_replace_callback("/\{{([a-z0-9]+?)\}}/i", function ($result)
use ($values) {
if (isset($result[1])) {
return $values[$result[1]];
}
}, $str);
The main issue is that {{[a-z]+}}
will match from {{name ... age}}
. Using the ?
makes the +
reluctant so it only matches up to the first }
rather than the last.
...however this only seems to match one pair of braces.
You forgot the escape the second {
/\{\{([a-zA-Z0-9]+)\}\}/
-^- -^-
In any case, try this regex, it's a bit shorter:
/\{\{([^}]+)\}\}/
Why don't you use sprintf
?
$template = '%s is %d years old';
$vars = array('name' => 'John Doe', 'age' => 27);
$output = sprintf($template, $vars['name'], $vars['age']);