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

2

8

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

Heliotherapy answered 21/9, 2009 at 13:1 Comment(0)
H
20
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);
}
Heliotherapy answered 21/9, 2009 at 13:3 Comment(2)
You should consider that the second parameter can also be an array for mapping.Putrefy
I didn't need that, but it would be more faithful to strtr's signature.Heliotherapy
S
3
    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.

Slumlord answered 22/12, 2013 at 4:32 Comment(1)
It works great. The accepted answer should be moved to this one.Dannie

© 2022 - 2024 — McMap. All rights reserved.