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

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

    I created this little function that replaces string on string (case-sensitive) with limit, without the need of Regexp. It works fine.

    function str_replace_limit($search, $replace, $string, $limit = 1) {
        $pos = strpos($string, $search);
    
        if ($pos === false) {
            return $string;
        }
    
        $searchLen = strlen($search);
    
        for ($i = 0; $i < $limit; $i++) {
            $string = substr_replace($string, $replace, $pos, $searchLen);
    
            $pos = strpos($string, $search);
    
            if ($pos === false) {
                break;
            }
        }
    
        return $string;
    }
    

    Example usage:

    $search  = 'foo';
    $replace = 'bar';
    $string  = 'foo wizard makes foo brew for evil foo and jack';
    $limit   = 2;
    
    $replaced = str_replace_limit($search, $replace, $string, $limit);
    
    echo $replaced;
    // bar wizard makes bar brew for evil foo and jack
    

提交回复
热议问题