解析字符串以插入变量的最佳方法是什么?

时间:2015-05-23 17:51:32

标签: php

我有一个这样的字符串:
"Hello, I am $name, it's nice to meet $noun".

它直接来自数据库,$被转义。我也有这样一个阵列:
[ 'name' => "Jawsh", 'noun' => "you" ]

如何用$string中的变量替换相应数组数据的值?

4 个答案:

答案 0 :(得分:2)

我会这样做:

$string = "Hello, I am \$name, it's nice to meet \$noun.";
$array = array('name' => "Jawsh",'noun' => "you");

echo preg_replace_callback('/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/', function($match) use ($array) {
    if (isset($array[$match[1]])) {
        return $array[$match[1]];
    }

    return $match[0];
}, $string);
  

变量名遵循与PHP中其他标签相同的规则。一个有效的   变量名以字母或下划线开头,后跟任意名称   字母,数字或下划线的数量。作为正则表达式,   它将被表达为:'[a-zA-Z_ \ x7f- \ xff] [a-zA-Z0-9_ \ x7f- \ xff] *'

http://php.net/manual/en/language.variables.basics.php

答案 1 :(得分:0)

试试这个:

$string = "Hello, I am $name, it's nice to meet $noun.";
$array = [
    'name' => "Jawsh",
    'noun' => "you"
]

$string = str_replace('$name', $array['name'], $string);
$string = str_replace('$noun', $array['noun'], $string);

答案 2 :(得分:0)

extract()eval()的简单示例:

extract($variables);
eval('$string = "' . $string . '";');

demo

答案 3 :(得分:0)

您可以将preg_replace()/e标志结合使用来实现此目的:

$string = "Hello, I am \$name, it's nice to meet \$noun";
$replacements = array('name' => 'Jawsh', 'noun' => 'you');
$result  = preg_replace('/\$([a-z]+)/e', '$replacements["$1"]', $string);
print $result;

以上内容将打印出Hello, I am Jawsh, it's nice to meet you

请注意,在PHP 5.5中不推荐使用e模式修饰符,从PHP 7.0开始删除