Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 749
joeforker Avatar asked Sep 21 '09 13:09

joeforker


People also ask

Does PHP use utf8?

The utf8_encode() function is an inbuilt function in PHP which is used to encode an ISO-8859-1 string to UTF-8.

What is the functionality of Strtr () function?

The strtr() function translates certain characters in a string. Note: If the from and to parameters are different in length, both will be formatted to the length of the shortest.


2 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);
}
like image 75
joeforker Avatar answered Oct 24 '22 17:10

joeforker


    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.

like image 43
Konstantin Voronov Avatar answered Oct 24 '22 18:10

Konstantin Voronov