dporb84480 2018-06-07 06:01
浏览 43
已采纳

如何在php中用array()替换字符串

I have a text like this,

$string = "I have some fruits like [name], [another_name] and [one_another_name]";

And an array like this,

$fruits_array = array("Banana", "Apple", "Orange");

Now, how can I replace the texts between braces by following array?

I want a result like this,

I have some fruits like Banana, Apple and Orange.

Please provide the actual solution.

Thanks in advance.

  • 写回答

5条回答 默认 最新

  • doucan957495 2018-06-07 06:27
    关注

    You might also use preg_replace_callback with a regex \[[^]]+\] to match an opening [, then match not a ] using a negated character class and then match ].

    In the callback use array_shift to shift an element off the beginning of the array and use that as the replacement.

    $string = "I have some fruits like [name], [another_name] and [one_another_name]";
    $fruits_array = array("Banana", "Apple", "Orange");
    
    $string = preg_replace_callback(
        '/\[[^]]+\]/',
        function ($matches) use (&$fruits_array) {
            return array_shift($fruits_array);
        },
        $string
    );
    
    echo $string;
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况