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

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

    Here's a simple class I created to wrap our slightly modified str_replace() functions.

    Our php::str_rreplace() function also allows you to carry out a reverse, limited str_replace() which can be very handy when trying to replace only the final X instance(s) of a string.

    These examples both use preg_replace().

    ' with ''
        *
        * @param string   $find
        * @param string   $replace
        * @param string   $subject
        * @param int      $replacement_limit | -1 to replace all references
        *
        * @return string
        */
        public static function str_replace($find, $replace, $subject, $replacement_limit = -1) {
            $find_pattern = str_replace('/', '\/', $find);
            return preg_replace('/' . $find_pattern . '/', $replace, $subject, $replacement_limit);
        }
    
        /**
        * str_replace() from the end of a string that can also be limited e.g. replace only the last instance of '
    ' with '' * * @param string $find * @param string $replace * @param string $subject * @param int $replacement_limit | -1 to replace all references * * @return string */ public static function str_rreplace($find, $replace, $subject, $replacement_limit = -1) { return strrev( self::str_replace(strrev($find), strrev($replace), strrev($subject), $replacement_limit) ); } }

提交回复
热议问题