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

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

    function str_replace_once($search, $replace, $subject) {
        $pos = strpos($subject, $search);
        if ($pos === false) {
            return $subject;
        }
    
        return substr($subject, 0, $pos) . $replace . substr($subject, $pos + strlen($search));
    }
    

提交回复
热议问题