Reputation: 469
I am just trying to get my head round str_replace and curly brackets / braces . With the following line, I know that typing {the_title} will get replaces with the array $some_runtime_generated_title , but what does the first value mean ($str_template) ?.
str_replace( $str_template, '{the_title}', $some_runtime_generated_title );
Say I wanted to do the following........
$dog='lassy';
{dog}
would output >> lassy
How would I do that in php ?
Upvotes: 0
Views: 890
Reputation: 1763
A simple use case of str_replace for place holder replacement would look like:
$paramNames = array("{name}", "{year}", "{salutation}");
$paramValues = array("Iain Simpson", "2012", "Alloha");
$text = "{salutation}, {name}! Happy {year}!";
str_replace($paramNames, $paramValues, $text);
$paramNames
and $paramValues
arrays have same number of values.
A more specific purpose function would be:
/* 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;
}
Usage example:
$text = process_template("{salutation}, {name}! Happy {year}!", array(
"name" => "Iain", "year" => 2012, "salutation" => "Alloha"
));
Here's an example of an object-oriented approach:
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;
}
}
Usage example:
$template = new TextTemplate("{salutation}, {name}! Happy {year}!");
$text = $template->apply(array("name" => "Iain", "year" => 2012, "salutation" => "Alloha"));
Upvotes: 2
Reputation: 18859
You practically gave the answer yourself:
<?php
$some_runtime_generated_title = 'generated title';
$str_template = 'This is the template in which you use {the_title}';
$parsed = str_replace( '{the_title}', $some_runtime_generated_title, $str_template );
echo $parsed;
Upvotes: 1