function substitute($string, $object) {
$o = is_object($object) ? get_object_vars($object) : $object;
if(preg_match_all('/\\\\?\{([^{}]+)\}/', $string, $matches)) {
$search = array();
$replace = array();
foreach($matches[0] as $k => $m) {
if(substr($m, 0, 1) == '\\')
continue;
$search[] = $m;
$replace[] = isset($o[$matches[1][$k]]) && is_scalar($o[$matches[1][$k]]) ? $o[$matches[1][$k]] : '';
}
if($search)
$string = str_replace($search, $replace, $string);
}
return $string;
}
Here are some sample usages
$template = '{greating}, my name is {name}';
//using an object
$object = new stdClass();
$object->greating = 'Hello';
$object->name = 'Bela';
echo substitute($template, $object); //Hello, my name is Bela
//using an associative array
echo substitute($template, array('greating' => 'Hello',
'name' => 'Bela'
)); //Hello, my name is Bela
If you are looking for a very advanced usage of template you'll probabily look for library like patTemplate
Aucun commentaire:
Enregistrer un commentaire