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条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用