public static function str_replace($search, $replace, $subject, &$count = 0, $use_enc = null)
{
$enc = self::$hab_enc;
if ($use_enc !== null) {
$enc = $use_enc;
}
if (self::$use_library == self::USE_MBSTRING) {
// if search is an array and replace is not, we need to make replace an array and pad it to the same number of values as search
if (is_array($search) && !is_array($replace)) {
$replace = array_fill(0, count($search), $replace);
}
// if search is an array and replace is as well, we need to make sure replace has the same number of values - pad it with empty strings
if (is_array($search) && is_array($replace)) {
$replace = array_pad($replace, count($search), '');
}
// if search is not an array, make it one
if (!is_array($search)) {
$search = array($search);
}
// if replace is not an array, make it one
if (!is_array($replace)) {
$replace = array($replace);
}
// if subject is an array, recursively call ourselves on each element of it
if (is_array($subject)) {
foreach ($subject as $k => $v) {
$subject[$k] = self::str_replace($search, $replace, $v, $count, $use_enc);
}
return $subject;
}
// now we've got an array of characters and arrays of search / replace characters with the same values - loop and replace them!
$search_count = count($search);
// we modify $search, so we can't include it in the condition next
for ($i = 0; $i < $search_count; $i++) {
// the values we'll match
$s = array_shift($search);
$r = array_shift($replace);
// to avoid an infinite loop if you're replacing with a value that contains the subject we get the position of each instance first
$positions = array();
$offset = 0;
while (self::strpos($subject, $s, $offset, $enc) !== false) {
// get the position
$pos = self::strpos($subject, $s, $offset, $enc);
// add it to the list
$positions[] = $pos;
// and set the offset to skip over this value
$offset = $pos + self::strlen($s, $enc);
}
// if we pick through from the beginning, our positions will change if the replacement string is longer
// instead, we pick through from the last place
$positions = array_reverse($positions);
// now that we've got the position of each one, just loop through that and replace them
foreach ($positions as $pos) {
// pull out the part before the string
$before = self::substr($subject, 0, $pos, $enc);
// pull out the part after
$after = self::substr($subject, $pos + self::strlen($s, $enc), null, $enc);
// now we have the string in two parts without the string we're searching for
// put it back together with the replacement
$subject = $before . $r . $after;
// increment our count, a replacement was made
$count++;
}
}
} else {
$subject = str_replace($search, $replace, $subject, $count);
}
return $subject;
}