使用 PHP 和/或 Codeigniter,我想创建一些字符串模板以存储在数据库中,以便稍后可以使用它们打印出自定义语句。
例如,我想将此 "hello %s! you are the %d visitor."
存储在我的数据库中,以便稍后我可以插入姓名和号码来打印此消息“你好鲍勃!你是第 100 位访客”
。
是否有任何可用的函数可以轻松地做到这一点,或者我是否必须使用 preg_match/preg_replace 编写自己的脚本?
这个有效:
<?
$test = 'hello %s';
$name = 'bob';
printf( $test, $name );
?>
最佳答案
你可以使用sprintf
,但您始终需要知道向模板提供参数的确切顺序。我会建议更多的东西
// this works only on php 5.3 and up
function sformat($template, array $params)
{
return str_replace(
array_map(
function($key)
{
return '{'.$key.'}';
}, array_keys($params)),
array_values($params), $template);
}
// or in the case of a php version < 5.3
function sformat($template, array $params)
{
$output = $template;
foreach($params as $key => $value)
{
$output = str_replace('{'.$key.'}', $value, $output);
}
return $output;
}
echo sformat('Hello, {what}!', array('what' => 'World'));
// outputs: "Hello, World!"
关于php - PHP/Codeigniter 的 Printf 语法解析器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3095774/