dsmupo6631 2012-10-17 06:56
浏览 80
已采纳

用句子替换不同值的单词

I have one sentence like this:

{pattern} test {pattern} how r u {pattern}

How can I replace {pattern} with different values like

{AAA} test {BBB} how r u {CCC}
  • 写回答

7条回答 默认 最新

  • dongxiegao3071 2012-10-17 07:11
    关注

    If you wish to replace the same pattern with something else every time you could consider using preg_replace_callback(). At every match, a function is executed and you can return a different string at every invocation:

    $s = '{pattern} test {pattern} how r u {pattern}';
    
    // this gets called at every match    
    function replace_pattern($match)
    {
        // list of replacement strings $a and a looping counter $i
        static $a = array('AAA', 'BBB', 'CCC');
        static $i = 0;
    
        // return current replacement string and increase counter
        return $a[$i++ % count($a)];
    }
    
    echo preg_replace_callback('/{pattern}/', 'replace_pattern', $s);
    

    This solution cycles the replacement strings, so it will replace like AAA, BBB, CCC, AAA (again), etc. The exact strategy you wish to adopt may be different.

    The second parameter to preg_replace_callback() may also be a closure (>= 5.3)

    Also, instead of using a regular function with static declarations, it might be more appropriate to use an object for state management.

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

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试