views:

471

answers:

2

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
You should consider that the second parameter can also be an array for mapping.
Gumbo
I didn't need that, but it would be more faithful to strtr's signature.
joeforker
A: 
function strtr_utf8($string, $from, $to)
{
    $string = utf8_decode($string);    
    $string = strtr($string, utf8_decode($from), $to);

    return utf8_encode($string);
}
Kieran Hall
-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