プレースホルダの交換のための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の精神を借りて)をお探しですか? –
この種の質問は、[マニュアルの速い把握](http://php.net/str_replace)で簡単に答えられます。それは例を持っています。私は人々がマニュアルなしでコードを管理する方法を理解できません。 –
私がここに来る前にマニュアルを読みましたが、わかりませんでした。何かを読んで理解するのは全く違っています。 –