PHP str_replace() with a limit param?

前端 未结 5 1954
猫巷女王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条回答
  •  旧时难觅i
    2020-12-17 19:22

    This is an enhanced version of @brad-christie's answer which ads compatibility for arrays as $find and $replace values:

    function str_replace_limit($find, $replacement, $subject, $limit = 0) {
    
        if ($limit == 0)
          return str_replace($find, $replacement, $subject);
    
        for ($i = 0; $i < count($find); $i++) {
          $find[$i] = '/' . preg_quote($find[$i],'/') . '/';
        }
    
        return preg_replace($find, $replacement, $subject, $limit);
      }
    

提交回复
热议问题