为了账号安全,请及时绑定邮箱和手机立即绑定

如何用php中的值替换字符串中的变量?

如何用php中的值替换字符串中的变量?

PHP
aluckdog 2019-11-18 18:13:37
我在数据库中有这样的字符串(实际字符串包含100s的单词和10s的变量)i am a {$club} fan我像这样回声这串 $club = "Barcelona";echo $data_base[0]['body'];我的输出是 i am a {$club} fan。我想要 i am a Barcelona fan 我该怎么做?
查看完整描述

3 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

使用strtr它将转换字符串的一部分。


$club = "Barcelona";

echo strtr($data_base[0]['body'], array('{$club}' => $club));

对于多个值(Demo):


$data_base[0]['body'] = 'I am a {$club} fan.'; // Tests


$vars = array(

  '{$club}'       => 'Barcelona',

  '{$tag}'        => 'sometext',

  '{$anothertag}' => 'someothertext'

);


echo strtr($data_base[0]['body'], $vars);

程序输出:


I am a Barcelona fan.


查看完整回答
反对 回复 2019-11-18
?
POPMUISE

TA贡献1765条经验 获得超5个赞

/**

 * A function to fill the template with variables, returns filled template.

 * 

 * @param string $template A template with variables placeholders {$varaible}.

 * @param array $variables A key => value store of variable names and values.

 * 

 * @return string  

 */


public function replaceVariablesInTemplate($template, array $variables){


 return preg_replace_callback('#{(.*?)}#',

       function($match) use ($variables){

            $match[1]=trim($match[1],'$');

            return $variables[$match[1]];

       },

       ' '.$template.' ');


}  


查看完整回答
反对 回复 2019-11-18
  • 3 回答
  • 0 关注
  • 1002 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信