I have a string, that can has simple templates. And I have an array with values for replacemenet. Currently I am doing it with loop. But I want to change it to preg_replace. Can
Something like the following?
<?php
$values = array(
'id' => 120,
'name' => 'Jim'
);
$string = 'Hello <!name!>. Your ID is <!id!>';
function foo($val) {
return '/<!' . $val . '!>/';
}
echo preg_replace(array_map('foo', array_keys($values)), array_values($values), $string);
If the whole thing is in a class:
class Template {
static function bar($val) {
return '/<!' . $val . '!>/';
}
function render($values, $string) {
echo preg_replace(array_map(array('Template', 'bar'), array_keys($values)), array_values($values), $string);
}
}
$values = array(
'id' => 120,
'name' => 'Jim'
);
$string = 'Hello <!name!>. Your ID is <!id!>';
$T = new Template();
$T->render($values, $string);