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

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

    This function is heavily inspired by the answer by @renocor. It makes the function multi byte safe.

    function str_replace_limit($search, $replace, $string, $limit)
    {
        $i = 0;
        $searchLength = mb_strlen($search);
    
        while(($pos = mb_strpos($string, $search)) !== false && $i < $limit)
        {
            $string = mb_substr_replace($string, $replace, $pos, $searchLength);
            $i += 1;
        }
    
        return $string;
    }
    
    function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
    {
        $string = (array)$string;
        $encoding = is_null($encoding) ? mb_internal_encoding() : $encoding;
        $length = is_null($length) ? mb_strlen($string) - $start : $length;
    
        $string = array_map(function($str) use ($replacement, $start, $length, $encoding){
    
            $begin = mb_substr($str, 0, $start, $encoding);
            $end = mb_substr($str, ($start + $length), mb_strlen($str), $encoding);
    
            return $begin . $replacement . $end;
    
        }, $string);
    
        return ( count($string) === 1 ) ? $string[0] : $string;
    }
    

提交回复
热议问题