1

我有以下代码。

<?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],没有任何效果!

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

4

1 回答 1

2

您需要使用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,而不是自己实现它。

于 2012-04-28T12:37:33.513 回答