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

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

    Can be done with preg_replace:

    function str_replace_first($from, $to, $content)
    {
        $from = '/'.preg_quote($from, '/').'/';
    
        return preg_replace($from, $to, $content, 1);
    }
    
    echo str_replace_first('abc', '123', 'abcdef abcdef abcdef'); 
    // outputs '123def abcdef abcdef'
    

    The magic is in the optional fourth parameter [Limit]. From the documentation:

    [Limit] - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).


    Though, see zombat's answer for a more efficient method (roughly, 3-4x faster).

提交回复
热议问题