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

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

    For a string

    $string = 'OOO.OOO.OOO.S';
    $search = 'OOO';
    $replace = 'B';
    
    //replace ONLY FIRST occurance of "OOO" with "B"
        $string = substr_replace($string,$replace,0,strlen($search));
        //$string => B.OOO.OOO.S
    
    //replace ONLY LAST occurance of "OOOO" with "B"
        $string = substr_replace($string,$replace,strrpos($string,$search),strlen($search)) 
        //$string => OOO.OOO.B.S
    
        //replace ONLY LAST occurance of "OOOO" with "B"
        $string = strrev(implode(strrev($replace),explode(strrev($search),strrev($string),2)))
        //$string => OOO.OOO.B.S
    

    For a single character

    $string[strpos($string,$search)] = $replace;
    
    
    //EXAMPLE
    
    $string = 'O.O.O.O.S';
    $search = 'O';
    $replace = 'B';
    
    //replace ONLY FIRST occurance of "O" with "B" 
        $string[strpos($string,$search)] = $replace;  
        //$string => B.O.O.O.S
    
    //replace ONLY LAST occurance of "O" with "B" 
        $string[strrpos($string,$search)] = $replace; 
        // $string => B.O.O.B.S
    

提交回复
热议问题