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

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

    There's no version of it, but the solution isn't hacky at all.

    $pos = strpos($haystack, $needle);
    if ($pos !== false) {
        $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
    }
    

    Pretty easy, and saves the performance penalty of regular expressions.


    Bonus: If you want to replace last occurrence, just use strrpos in place of strpos.

提交回复
热议问题