Замена подстроки с использованием str_replace - PullRequest
0 голосов
/ 03 января 2012

Я просто пытаюсь обернуть голову str_replace и фигурными скобками / скобками.Со следующей строкой я знаю, что при наборе {the_title} будет получено замещение на массив $ some_runtime_generated_title, но что означает первое значение ($ str_template)?........

$dog='lassy';
{dog}
would output >> lassy

Как мне это сделать в php?

Ответы [ 2 ]

2 голосов
/ 03 января 2012

Простой вариант использования 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"));
1 голос
/ 03 января 2012

Вы практически дали ответ сами:

<?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;
...