【发布时间】:2018-06-18 11:14:51
【问题描述】:
我正在使用 PHP 7.2.4,我想做一个模板引擎项目, 我尝试使用 preg_replace 更改字符串中的变量, 代码在这里:
<?php
$lang = array(
'hello' => 'Hello {$username}',
'error_info' => 'Error Information : {$message}',
'admin_denied' => '{$current_user} are not Administrator',
);
$username = 'Guest';
$current_user = 'Empty';
$message = 'You are not member !';
$new_string = preg_replace_callback('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', 'test', $string);
function test($matches)
{
return '<?php echo '.$matches[1].'; ?>';
}
echo $new_string;
但它只是告诉我
Hello , how are you?
它会自动删除变量...
更新: 这里是 var_dump:
D:\Wamp\www\t.php:5:string 'Hello <?php echo $username; ?>, how are you?' (length=44)
【问题讨论】:
-
preg_replace_callback -
This is an example how you can do it。定义一个关联数组而不是单独的变量,并用它来替换匹配项。
-
@WiktorStribiżew 是的!非常感谢~
标签: php preg-replace template-engine