动态str_replace变量(不知道名称)

时间:2014-09-20 08:56:56

标签: php str-replace

我有一个数据库,页面内容包含一些变量,用于exmpale [var1],[name],[foo],..

页面示例:

  

hi [name],

     你是[var1]还是[foo]?

所有这些变量都应该替换为输出上相应的php变量

[var1]成为$ var1 [name]成为$ name

我知道我可以手动使用str_replace来更改此变量,例如:

echo( str_replace( array( [var1], [name], [foo] ), array( $var1, $name, $foo), $page ));

但是有一种方法可以创建一个自动替换所有这些变量的循环吗?

2 个答案:

答案 0 :(得分:0)

让我们考虑一个包含一些字符串的数组,如下所示:

array("var1","name","foo")

所以这是解决方案:

<?php
$rowdata=array("var1","name","foo");

foreach($rowdata as $key=>$value){
$rowdata[$key]="$".$value;
}

echo '<pre>';
print_r($rowdata);
echo '</pre>';

&GT;

答案 1 :(得分:0)

试试这段代码。这是工作。首先找到括号中的所有这些字符串。然后使用preg_replace替换内容。

$text = '[This] is a [test] string, [try] it.';
preg_match_all("^\[(.*?)\]^", $text, $matches);
$data = array_combine($matches[1],$matches[1]);

foreach($data as $key =>$value)
{
$text = preg_replace('/\['.$key.'\]/', '$'.$value, $text);

}
echo $text;