I'm looking for a UTF-8 compatible strtr for PHP.
Asked
Active
Viewed 9,350 times
2 Answers
18
function strtr_utf8($str, $from, $to) {
$keys = array();
$values = array();
preg_match_all('/./u', $from, $keys);
preg_match_all('/./u', $to, $values);
$mapping = array_combine($keys[0], $values[0]);
return strtr($str, $mapping);
}

joeforker
- 40,459
- 37
- 151
- 246
-
6You should consider that the second parameter can also be an array for mapping. – Gumbo Sep 21 '09 at 13:14
-
I didn't need that, but it would be more faithful to strtr's signature. – joeforker Sep 21 '09 at 13:29
3
function strtr_utf8($str, $from, $to) { $keys = array(); $values = array(); if(!is_array($from)) { preg_match_all('/./u', $from, $keys); preg_match_all('/./u', $to, $values); $mapping = array_combine($keys[0], $values[0]); }else $mapping=$from; return strtr($str, $mapping); }
I slightly edited the joeforker's function to return back the functionality of using second parameter as array for replace_pairs.

Konstantin Voronov
- 140
- 1
- 5