php - PHP preg_replace 变量中的字符串
问题描述
我正在使用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
回调函数中检查是否有一个名为找到捕获的键。如果是,则替换为相应的值,否则,替换为匹配项以将其放回找到的位置。
这是PHP 中的示例代码:
$values = array('username'=>'AAAAAA', 'lastname'=>'Smith');
$string = 'Hello {$username}, how are you?';
$new_string = preg_replace_callback('/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}/', function($m) use ($values) {
return 'Hello <?php echo ' . (!empty($values[$m[1]]) ? $values[$m[1]] : $m[0]) . '; ?>';
}, $string);
var_dump($new_string);
输出:
string(47) "Hello Hello <?php echo AAAAAA; ?>, how are you?"
注意模式charnge,我在后面移动了括号$
:
\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}
^ ^
实际上,您甚至可以将其缩短为
\{\$([a-zA-Z_\x7f-\xff][\w\x7f-\xff]*)}
^^
推荐阅读
- ios - SwiftUI - 在“onAppear”中更改属性在呈现时不会更改工作表
- python - 如何将 SQL 查询转换为 django ORM
- .net - 在 vb.net 中使用 Request.Url.AbsolutePath 时如何防止 xss
- python-3.x - 我是否使用循环、df.melt 或 df.explode 来实现扁平化数据框?
- vb.net - vb.net 我正在尝试调整控件(标签、文本框、richtextbox)的大小,使其成为包含给定字符串的最小正方形
- python - 'with' 语句在 kivy 中如何工作?
- wordpress - Heroku 应用程序名称重命名仍然引用旧应用程序 url
- android - 我如何从父项目中打开子库的活动
- php - 在ajax发布后下载生成的pdf
- python - Python SQLITE 不更新值