douan3019 2014-03-07 13:28
浏览 327

PHP将第一次出现替换为x,将第二次出现的字符串替换为y

This is a tricky question here is what I am trying to do:

$str="abc def abc";

I want to replace first occurrence of abc with 123 and second occurrence of abc with 456 Now with preg_match it is possible that I replace first occurrence of abc with 123 like this

preg_replace('/abc/', '123', $str, 1);

But how to replace the second occurrence with 456 and most importantly how to do it at once and generate the required string (i.e 123 def 456).

Note: Strings are generated from external source.

Thanks Ahmar

  • 写回答

4条回答 默认 最新

  • douyuanliao8815 2014-03-07 13:30
    关注

    You were very close:

    $str = preg_replace('/abc/', '123', $str, 1); // will replace first 'abc'
    $str = preg_replace('/abc/', '456', $str);    // will replace all others
    

    The reason this will work, is because the 2nd regex's first occurence, is actually the 2nd item.
    Pro: Very readable, very easy to understand and implement
    Con: the string will be regexed twice (bad for large strings), options are limited


    If this is not what you want, you can use preg_replace_callback()

    $firstHasBeenFound = false;
    function magicFunction($matches){
        global $firstHasBeenFound;
        print_r($matches);
        if( !$firstHasBeenFound ){
            /* do something for the first time */ ;
            $firstHasBeenFound = true; // save for next round
        }
        else{
             /* do something for the test */ ;
        }
    }
    
    $str = preg_replace_callback('/abc/', 'magicFunction', $str);
    

    Pro: A lot more variants can be made, more control over code, only one parse of the string
    Con: More difficult to read/implement

    In this example I use $firstHasBeenFound, but you could use a increment to do something each 2nd, or something when you find match 7, etc

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料