如何用PHP中的值替换字符串中的变量? [英] How can I replace a variable in a string with the value in PHP?

查看:506
本文介绍了如何用PHP中的值替换字符串中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有这样的字符串(实际的字符串包含100s的单词和10s的变量):

I have string like this in database (the actual string contains 100s of word and 10s of variable):

I am a {$club} fan

我像这样回显此字符串:

I echo this string like this:

$club = "Barcelona";
echo $data_base[0]['body'];

我的输出是I am a {$club} fan.我要I am a Barcelona fan.我该怎么办?

My output is I am a {$club} fan. I want I am a Barcelona fan. How can I do this?

推荐答案

使用 strtr .它将翻译字符串的一部分.

Use strtr. It will translate parts of a string.

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


对于多个值(演示):

$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.

这篇关于如何用PHP中的值替换字符串中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆