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

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

    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.

提交回复
热议问题