$name = "MasterOfDisaster";
$age = "666";
$string = "My name is [name] and i'm [age] years old";
现在我'想要替换两个字符之间的所有值,并将它们更改为相同的命名php变量
[foo] > $foo
I want to get this without replacing with arrays:
$string = "My name is $name and i'm $age years old";
我可以用ereg_replace实现这个目标吗?我不想将str_replace()与数组结合使用来捕获文本中的所有值。
到目前为止我的preg_replace():
$placeholder = preg_replace("/\[(.*?)]/", ${"$1"}, $string);
echo $placeholder;
答案 0 :(得分:0)
您可以这样使用:
$array = array('name' => "MasterOfDisaster", 'age' => "666");
$string = "My name is [name] and i'm [age] years old";
foreach ($array as $key => $value) {
$string = preg_replace('/\['.$key.'\]/i', $value, $string);
}
echo $string;
输出是:
My name is MasterOfDisaster and i'm 666 years old
注意:不要使用ereg_replace
函数,因为它已被弃用。 Yous preg_replace
起作用。