像下面这样的东西?
<?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);
如果整个事情是一个类:
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);
我可能会使用'preg_replace_callback'和闭合。 – 2012-03-20 09:34:21