如何用实际值替换占位符?

时间:2012-01-13 05:12:28

标签: php

我需要一个用正确的变量替换'{}'中的每个variable_name的函数。 像这样:

$data["name"] = "Johnny";
$data["age"] = "20";

$string = "Hello my name is {name} and I'm {age} years old.";

$output = replace($string, $data);
echo $output;

//outputs: Hello my name is Johnny and I'm 20 years old.

我知道有这样的框架/引擎,但我不想为此安装一堆文件。

6 个答案:

答案 0 :(得分:11)

使用/e的{​​{1}}修饰符

,您可以轻松完成此操作
preg_replace

<强> See it in action

您可能希望自定义与替换字符串匹配的模式(此处为$data["name"] = "Johnny"; $data["age"] = "20"; $string = "Hello my name is {name} and I'm {age} years old."; echo preg_replace('/{(\w+)}/e', '$data["\\1"]', $string); :大括号之间的一个或多个字母数字字符或下划线)。把它放到一个函数中是微不足道的。

答案 1 :(得分:2)

你走了:

$data["name"] = "Johnny";
$data["age"] = "20";

$string = "Hello my name is {name} and I'm {age} years old.";

foreach ($data as $key => $value) {
$string = str_replace("{".$key."}", $value, $string);
}

echo $string;

答案 2 :(得分:0)

您可能需要查看preg_replace功能。

答案 3 :(得分:0)

$string = "Hello my name is {$data["name"]} and I'm {$data["age"]} years old.";

会做你想要的。如果它不适合你,请尝试使用正则表达式循环,如此

for ($data as $key=>$value){
    $string = preg_replace("\{$key\}", $value, $string);
}

未经测试,您可能需要查阅文档。

答案 4 :(得分:0)

您可以试用vsprintf语法略有不同

$string = 'hello my name is %s and I am %d years old';

$params = array('John', 29);

var_dump(vsprintf($string, $params));
//string(43) "hello my name is John and I am 29 years old" 

答案 5 :(得分:0)

I've always been a fan of strtr.

$ php -r 'echo strtr("Hi @name. The weather is @weather.", ["@name" => "Nick", "@weather" => "Sunny"]);'
Hi Nick. The weather is Sunny.

The other advantage to this is you can define different placeholder prefix types. This is how Drupal does it; @ indicates a string to be escaped as safe to output to a web page (to avoid injection attacks). The format_string command loops over your parameters (such as @name and @weather) and if the first character is an @, then it uses check_plain on the value.

Also answered here: https://stackoverflow.com/a/36781566/224707