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

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

    => CODE WAS REVISED, so consider some comments too old

    And thanks everyone on helping me to improve that

    Any BUG, please communicate me; I'll fix that up right after

    So, lets go for:

    Replacing the first 'o' to 'ea' for example:

    $s='I love you';
    $s=str_replace_first('o','ea',$s);
    echo $s;
    
    //output: I leave you
    

    The function:

    function str_replace_first($a,$b,$s)
             {
             $w=strpos($s,$a);
             if($w===false)return $s;
             return substr($s,0,$w).$b.substr($s,$w+strlen($a));
             }
    
    0 讨论(0)
  • 2020-11-22 11:46

    Complementing what people said, remember that the entire string is an array:

    $string = "Lorem ipsum lá lá lá";
    
    $string[0] = "B";
    
    echo $string;
    

    "Borem ipsum lá lá lá"

    0 讨论(0)
  • 2020-11-22 11:46

    For Loop Solution

    <?php
    echo replaceFirstMatchedChar("&", "?", "/property/details&id=202&test=123#tab-6");
    
    function replaceFirstMatchedChar($searchChar, $replaceChar, $str)
    {
        for ($i = 0; $i < strlen($str); $i++) {
    
            if ($str[$i] == $searchChar) {
                $str[$i] = $replaceChar;
                break;
            }
        }
        return $str;
    }
    
    0 讨论(0)
  • 2020-11-22 11:46
    $str = "Hello there folks!"
    $str_ex = explode("there, $str, 2);   //explodes $string just twice
                                          //outputs: array ("Hello ", " folks")
    $str_final = implode("", $str_ex);    // glues above array together
                                          // outputs: str("Hello  folks")
    

    There is one more additional space but it didnt matter as it was for backgound script in my case.

    0 讨论(0)
  • 2020-11-22 11:51

    Edit: both answers have been updated and are now correct. I'll leave the answer since the function timings are still useful.

    The answers by 'zombat' and 'too much php' are unfortunately not correct. This is a revision to the answer zombat posted (as I don't have enough reputation to post a comment):

    $pos = strpos($haystack,$needle);
    if ($pos !== false) {
        $newstring = substr_replace($haystack,$replace,$pos,strlen($needle));
    }
    

    Note the strlen($needle), instead of strlen($replace). Zombat's example will only work correctly if needle and replace are the same length.

    Here's the same functionality in a function with the same signature as PHP's own str_replace:

    function str_replace_first($search, $replace, $subject) {
        $pos = strpos($subject, $search);
        if ($pos !== false) {
            return substr_replace($subject, $replace, $pos, strlen($search));
        }
        return $subject;
    }
    

    This is the revised answer of 'too much php':

    implode($replace, explode($search, $subject, 2));
    

    Note the 2 at the end instead of 1. Or in function format:

    function str_replace_first($search, $replace, $subject) {
        return implode($replace, explode($search, $subject, 2));
    }
    

    I timed the two functions and the first one is twice as fast when no match is found. They are the same speed when a match is found.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题