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

后端 未结 22 1316
醉酒成梦
醉酒成梦 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 11:42

    To expand on zombat's answer (which I believe to be the best answer), I created a recursive version of his function that takes in a $limit parameter to specify how many occurrences you want to replace.

    function str_replace_limit($haystack, $needle, $replace, $limit, $start_pos = 0) {
        if ($limit <= 0) {
            return $haystack;
        } else {
            $pos = strpos($haystack,$needle,$start_pos);
            if ($pos !== false) {
                $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
                return str_replace_limit($newstring, $needle, $replace, $limit-1, $pos+strlen($replace));
            } else {
                return $haystack;
            }
        }
    }
    

提交回复
热议问题