Using str_replace so that it only acts on the first match?

后端 未结 22 1199
醉酒成梦
醉酒成梦 2020-11-22 11:03

I want a version of str_replace() that only replaces the first occurrence of $search in the $subject. Is there an easy solution to thi

22条回答
  •  轮回少年
    2020-11-22 11:58

    According to my test result, I'd like to vote the regular_express one provided by karim79. (I don't have enough reputation to vote it now!)

    The solution from zombat uses too many function calls, I even simplify the codes. I'm using PHP 5.4 to run both solutions for 100,000 times, and here's the result:

    $str = 'Hello abc, have a nice day abc! abc!';
    $pos = strpos($str, 'abc');
    $str = substr_replace($str, '123', $pos, 3);
    

    ==> 1.85 sec

    $str = 'Hello abc, have a nice day abc! abc!';
    $str = preg_replace('/abc/', '123', $str, 1);
    

    ==> 1.35 sec

    As you can see. The performance of preg_replace is not so bad as many people think. So I'd suggest the classy solution if your regular express is not complicated.

提交回复
热议问题