[3] | 1 | <?php |
---|
| 2 | |
---|
| 3 | /** |
---|
| 4 | * @version $Id: str_ireplace.php,v 1.2 2007/08/12 01:20:46 harryf Exp $ |
---|
| 5 | * @package utf8 |
---|
| 6 | * @subpackage strings |
---|
| 7 | */ |
---|
| 8 | |
---|
| 9 | /** |
---|
| 10 | * UTF-8 aware alternative to str_ireplace |
---|
| 11 | * Case-insensitive version of str_replace |
---|
| 12 | * Note: requires utf8_strtolower |
---|
| 13 | * Note: it's not fast and gets slower if $search / $replace is array |
---|
| 14 | * Notes: it's based on the assumption that the lower and uppercase |
---|
| 15 | * versions of a UTF-8 character will have the same length in bytes |
---|
| 16 | * which is currently true given the hash table to strtolower |
---|
| 17 | * @param string |
---|
| 18 | * @return string |
---|
| 19 | * @see http://www.php.net/str_ireplace |
---|
| 20 | * @see utf8_strtolower |
---|
| 21 | * @package utf8 |
---|
| 22 | * @subpackage strings |
---|
| 23 | */ |
---|
| 24 | function utf8_ireplace($search, $replace, $str, $count=null) |
---|
| 25 | { |
---|
| 26 | if (!is_array($search)) |
---|
| 27 | { |
---|
| 28 | $slen = strlen($search); |
---|
| 29 | |
---|
| 30 | if ($slen == 0) |
---|
| 31 | return $str; |
---|
| 32 | |
---|
| 33 | $lendif = strlen($replace) - strlen($search); |
---|
| 34 | $search = utf8_strtolower($search); |
---|
| 35 | |
---|
| 36 | $search = preg_quote($search); |
---|
| 37 | $lstr = utf8_strtolower($str); |
---|
| 38 | $i = 0; |
---|
| 39 | $matched = 0; |
---|
| 40 | |
---|
| 41 | while (preg_match('/(.*)'.$search.'/Us', $lstr, $matches)) |
---|
| 42 | { |
---|
| 43 | if ($i === $count) |
---|
| 44 | break; |
---|
| 45 | |
---|
| 46 | $mlen = strlen($matches[0]); |
---|
| 47 | $lstr = substr($lstr, $mlen); |
---|
| 48 | $str = substr_replace($str, $replace, $matched+strlen($matches[1]), $slen); |
---|
| 49 | $matched += $mlen + $lendif; |
---|
| 50 | $i++; |
---|
| 51 | } |
---|
| 52 | |
---|
| 53 | return $str; |
---|
| 54 | } |
---|
| 55 | else |
---|
| 56 | { |
---|
| 57 | foreach (array_keys($search) as $k) |
---|
| 58 | { |
---|
| 59 | if (is_array($replace)) |
---|
| 60 | { |
---|
| 61 | if (array_key_exists($k, $replace)) |
---|
| 62 | $str = utf8_ireplace($search[$k], $replace[$k], $str, $count); |
---|
| 63 | else |
---|
| 64 | $str = utf8_ireplace($search[$k], '', $str, $count); |
---|
| 65 | } |
---|
| 66 | else |
---|
| 67 | $str = utf8_ireplace($search[$k], $replace, $str, $count); |
---|
| 68 | } |
---|
| 69 | |
---|
| 70 | return $str; |
---|
| 71 | } |
---|
| 72 | } |
---|