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

后端 未结 22 1350
醉酒成梦
醉酒成梦 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:46

    => CODE WAS REVISED, so consider some comments too old

    And thanks everyone on helping me to improve that

    Any BUG, please communicate me; I'll fix that up right after

    So, lets go for:

    Replacing the first 'o' to 'ea' for example:

    $s='I love you';
    $s=str_replace_first('o','ea',$s);
    echo $s;
    
    //output: I leave you
    

    The function:

    function str_replace_first($a,$b,$s)
             {
             $w=strpos($s,$a);
             if($w===false)return $s;
             return substr($s,0,$w).$b.substr($s,$w+strlen($a));
             }
    

提交回复
热议问题