代码之家  ›  专栏  ›  技术社区  ›  joeforker

如何在PHP中对utf-8执行strtr?

  •  7
  • joeforker  · 技术社区  · 16 年前

    我正在为PHP寻找一个兼容UTF-8的strtr。

    3 回复  |  直到 9 年前
        1
  •  14
  •   joeforker    16 年前
    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);
    }
    
        2
  •  2
  •   Konstantin Voronov    11 年前
        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);
        }
    

    我稍微编辑了joefooker的函数,返回使用第二个参数作为数组替换_对的功能。

        3
  •  -1
  •   Leonardo Filipe    9 年前
        $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);