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"));
您是否在为PHP寻找模板引擎(本着MustacheJS的精神)? – 2012-01-03 09:57:45
这种问题很容易用[手册快速掌握](http://php.net/str_replace)来回答。它甚至有例子。我无法理解人们如何在没有手册的情况下编码。 – 2012-01-03 10:13:29
我在来这里之前阅读手册,但是我不理解它,阅读和理解它们完全不同。 – 2012-01-03 10:25:30