2 回答

TA贡献1851条经验 获得超3个赞
你最好使用类似的东西sprintf
。
例如,如果你的数据库中有这个:
Hello, your name is %s
你可以像这样格式化它:
echo sprintf($row["heName"], "Test");
这将输出:
Hello, your name is Test
如果你真的想使用 PHP 风格的变量名,一种方法是用preg_replace_callback
它们各自的值替换变量:
<?php
function format_string($string, $variables) {
return preg_replace_callback("~\\$([A-Za-z0-9-_]+)~",
function($match) use (&$variables) {
$varname = $match[1];
return $variables[$varname];
}, $string);
}
echo format_string("Hello \$user", /* variable table */ [
"user" => "Test"
]);

TA贡献1802条经验 获得超5个赞
您可以使用评估...
$name = "jinko";
$helloname = "hello $name";
eval("\$helloname = \"$helloname\";");
echo $helloname; // prints: hello jinko
警告:这可能很危险,因为 eval 会“执行”任何 PHP 代码。因此,仅当来自数据库的数据安全时才使用它。
- 2 回答
- 0 关注
- 114 浏览
添加回答
举报