Home » Php » unicode – How do I do a strtr on UTF-8 in PHP?

unicode – How do I do a strtr on UTF-8 in PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m looking for a UTF-8 compatible strtr for PHP.

How to&Answers:
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);
}

Answer:

    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.

Answer:

    $fromto = array(
    'À'=>'A','Á'=>'A','Ã'=>'A','Â'=>'A',
    'É'=>'E','Ê'=>'E',
    'Í'=>'I',
    'Ó'=>'O','Õ'=>'O','Ô'=>'O',
    'Ú'=>'U','Ü'=>'U',
    'Ç'=>'C',
    'á'=>'a','à'=>'a','ã'=>'a','â'=>'a',
    'é'=>'e',
    'ê'=>'e',
    'í'=>'i',
    'ó'=>'o','õ'=>'o','ô'=>'o',
    'ç'=>'c'
    );
    $filter = strtr($filter,$fromto);