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