PHP str_replace() with a limit param?

前端 未结 5 1934
猫巷女王i
猫巷女王i 2020-12-17 18:38

str_replace replaces all occurrences of a word with a replacement.

preg_replace replaces occurrences of a pattern with a replacement and ta

5条回答
  •  自闭症患者
    2020-12-17 19:26

    function str_replace2($find, $replacement, $subject, $limit = 0){
      if ($limit == 0)
        return str_replace($find, $replacement, $subject);
      $ptn = '/' . preg_quote($find,'/') . '/';
      return preg_replace($ptn, $replacement, $subject, $limit);
    }
    

    That will allow you to place a limit on the number of replaces. Strings should be escaped using preg_quote to make sure any special characters aren't interpreted as a pattern character.

    Demo, BTW


    In case you're interested, here's a version that includes the &$count argument:

    function str_replace2($find, $replacement, $subject, $limit = 0, &$count = 0){
      if ($limit == 0)
        return str_replace($find, $replacement, $subject, $count);
      $ptn = '/' . preg_quote($find,'/') . '/';
      return preg_replace($ptn, $replacement, $subject, $limit, $count);
    }
    

提交回复
热议问题