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.

图片转代码服务由CSDN问答提供 功能建议

我有这样的文字,

  $ string =  “我有一些水果,如[name],[another_name]和[one_another_name]”; 
   
 
 

和这样的数组,

  $ fruits_array = array(“Banana”,“Apple”,“Orange”); 
   
 
 

现在,如何替换之间的文本 通过以下数组括起来?

我想要一个这样的结果, <前> 我有一些水果,如Banana,Apple和Orange。

请提供实际解决方案。

提前致谢。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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

相关推荐 更多相似问题