使用str_replace替换子串

时间:2012-01-03 09:51:29

标签: php str-replace

我只是试图让我的头围绕str_replace和花括号/大括号。 使用以下行,我知道输入{the_title}将替换为数组$ some_runtime_generated_title,但第一个值是什么意思($ str_template)?。

str_replace( $str_template, '{the_title}', $some_runtime_generated_title );

说我想做以下事情........

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

我将如何在PHP中执行此操作?

2 个答案:

答案 0 :(得分:2)

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 :(得分:1)

你几乎自己给出了答案:

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