preg_replace - 数组中的随机单词


preg_replace - random word in array

我有以下代码。

<?php
$user['username'] = 'Bastian';
$template = 'Hello {user:username}';
$template = preg_replace('/'{user':([a-zA-Z0-9]+)'}/', $user[''1'], $template);
echo $template;
// Output: 
// Notice: Undefined index: '1 in C:'xampp'htdocs'test.php on line 5
// Hello

我想,你知道我会做什么(我希望你知道)。我尝试替换$user["$1"],$user["$1"]或$user[$1],没有任何效果!

我希望你能帮助我的=)提前谢谢你!

你需要使用

preg_replace_callback() - preg_replace()的替换是一个字符串,所以你不能在那里使用 PHP 代码。不,/e修饰符不是解决方案,因为 eval 是邪恶的。

这里有一个例子(它需要 PHP 5.3,但无论如何你都应该使用最新版本!

$user['username'] = 'FooBar';
$template = 'Hello {user:username}';
echo preg_replace_callback('/'{user':([a-zA-Z0-9]+)'}/', function($m) use ($user) {
    return $user[$m[1]];
}, $template);

如果你必须使用旧的PHP版本,你可以这样做。不过,由于使用了全局变量,它要丑得多:

function replace_user($m) {
    global $user;
    return $user[$m[1]];
}
echo preg_replace_callback('/'{user':([a-zA-Z0-9]+)'}/', 'replace_user', $template);

但是,请考虑使用h2o 等模板引擎,而不是自己实现它。