I'm looking for a UTF-8 compatible strtr for PHP.
+4
A:
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
2009-09-21 13:03:02
You should consider that the second parameter can also be an array for mapping.
Gumbo
2009-09-21 13:14:39
I didn't need that, but it would be more faithful to strtr's signature.
joeforker
2009-09-21 13:29:37
A:
function strtr_utf8($string, $from, $to)
{
$string = utf8_decode($string);
$string = strtr($string, utf8_decode($from), $to);
return utf8_encode($string);
}
Kieran Hall
2009-09-21 13:09:45
-1 ISO 8859-1, the charset `utf8_decode` mapps to, is only a fraction of Unicode (first 256 characters). Any other character of Unicode will be discarded.
Gumbo
2009-09-21 13:22:28