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

用多个变量替换多个字符串

用多个变量替换多个字符串

PHP
米脂 2021-11-13 17:03:20
我想将所有开头的字符串更改{" and ending with "}为变量,例如:Hello {username}, -> to Hello $array['username']Your Country is {country}, -> Your Country is $array['country']但是我使用一个变量(Mysql)从数据库中获取所有字符串文本 $array['content']我想要的是:str_replace("{$whatinhere}",$array['$copytohere'],$array['content']);str_replace("{company}",$array['company'],$array['content']);
查看完整描述

3 回答

?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

使用 preg_replace_callback 函数


echo preg_replace_callback('~{(.+?)}~', 

        function($x) use ($array) { return isset($array[$x[1]]) ? $array[$x[1]] : ''; }, 

        $array['content']);


查看完整回答
反对 回复 2021-11-13
?
BIG阳

TA贡献1859条经验 获得超6个赞

我觉得你应该试试这个...


$content = $array['content'];


$mainContent = str_replace('{username}', $array['username'], $content);


$mainContent = str_replace('{company}', $array['company'], $mainContent);


echo $mainContent;


查看完整回答
反对 回复 2021-11-13
?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

据我了解,该$array变量包含占位符键/值对以及内容。您可以尝试使用以下代码将所有占位符键替换为其相应的值:


foreach ($array as $key => $value) {

    if ($key != "content") {

        $array["content"] = str_replace("{" . $key . "}", $value, $array["content"]);

    }

}


/** Print contents */

echo $array["content"];


查看完整回答
反对 回复 2021-11-13
  • 3 回答
  • 0 关注
  • 199 浏览

添加回答

举报

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