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

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

    You can use this:

    function str_replace_once($str_pattern, $str_replacement, $string){ 
    
            if (strpos($string, $str_pattern) !== false){ 
                $occurrence = strpos($string, $str_pattern); 
                return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern)); 
            } 
    
            return $string; 
        } 
    

    Found this example from php.net

    Usage:

    $string = "Thiz iz an examplz";
    var_dump(str_replace_once('z','Z', $string)); 
    

    Output:

    ThiZ iz an examplz
    

    This may reduce the performance a little bit, but the easiest solution.

提交回复
热议问题