Простой вариант использования str_replace для замены заполнителя будет выглядеть так:
$paramNames = array("{name}", "{year}", "{salutation}");
$paramValues = array("Iain Simpson", "2012", "Alloha");
$text = "{salutation}, {name}! Happy {year}!";
str_replace($paramNames, $paramValues, $text);
Массивы
$paramNames
и $paramValues
имеют одинаковое количество значений.
Более конкретная целевая функция будет:
/* Processes a text template by replacing {param}'s with corresponding values. A variation fo this function could accept a name of a file containing the template text. */
/* Parameters: */
/* template - a template text */
/* params - an assoc array (or map) of template parameter name=>value pairs */
function process_template($template, $params) {
$result = $template;
foreach ($params as $name => $value) {
// echo "Replacing {$name} with '$value'"; // echo can be used for debugging purposes
$result = str_replace("{$name}", $value, $result);
}
return $result;
}
Пример использования:
$text = process_template("{salutation}, {name}! Happy {year}!", array(
"name" => "Iain", "year" => 2012, "salutation" => "Alloha"
));
Вот пример объектно-ориентированного подхода:
class TextTemplate {
private static $left = "{";
private static $right = "}";
private $template;
function __construct($template) {
$this->template = $template;
}
public function apply($params) {
$placeholders = array();
$values = array();
foreach($params as $name => $value) {
array_push($placeholders, self::$left . $name . self::$right);
array_push($values, $value);
}
$result = str_replace($placeholders, $values, $this->template);
return $result;
}
}
Пример использования:
$template = new TextTemplate("{salutation}, {name}! Happy {year}!");
$text = $template->apply(array("name" => "Iain", "year" => 2012, "salutation" => "Alloha"));