Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP str_replace() with a limit param?

Tags:

php

str_replace replaces all occurrences of a word with a replacement.

preg_replace replaces occurrences of a pattern with a replacement and takes an optional limit param.

I don't have any need for pattern matching but would like the convenience of a limit param. What should I be using?

like image 941
buley Avatar asked Dec 14 '11 19:12

buley


2 Answers

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);
  }
like image 111
Parks Avatar answered Sep 21 '22 17:09

Parks


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);
}
like image 39
Brad Christie Avatar answered Sep 17 '22 17:09

Brad Christie