joeforker
joeforker

Reputation: 41747

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

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

Upvotes: 8

Views: 9645

Answers (2)

Konstantin Voronov
Konstantin Voronov

Reputation: 140

    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.

Upvotes: 3

joeforker
joeforker

Reputation: 41747

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);
}

Upvotes: 20

Related Questions