note 84917 deleted from function.str-ireplace by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Mar 2009 13:45:44 +0000 |
| Subject: | note 84917 deleted from function.str-ireplace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-151585@lists.php.net to get a copy of this message | ||
Note Submitter: a dot lyskawa at pp-layouts dot com
----
It's obvious str_ireplace() won't be multi-byte safe. Function mb_str_ireplace() is
missing in php, so here's mine:
<?php
/**
* Case insensitive multi-byte safe str_replace
* @param string $search
* @param string $replace
* @param string $subject
* @param int $count
* @param string $encoding
* @return string
*/
function mb_str_ireplace($search, $replace, $subject, $count = null, $encoding = 'utf-8')
{
$l1 = mb_strlen($search, $encoding);
$rc = 0;
$offset = 0;
while (ok($p = mb_stripos($subject, $search, $offset, $encoding)) && (is_null($rc) || $rc
<= $count)) {
if (ok($p)) $subject = mb_substr($subject, $offset, $p, $encoding) . $replace .
mb_substr($subject, $p + $l1, mb_strlen($subject, $encoding), $encoding);
$offset = $p + $l1;
$rc++;
}
return $subject;
}
?>
It works exactly like original str_ireplace() and defaults to 'utf-8' encoding. Replace
with null if you like. Well, it's surely slower than built-in functions, however it's one
of the fastest ways to do the trick.