我正在使用我在Stackoverflow上找到的函数来替换一些特殊字符:
function toASCII( $str )
{
return strtr(utf8_decode($str),
utf8_decode(
'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝŐŰßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿőű'),
'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYOUsaaaaaaaceeeeiiiionoooooouuuuyyou');
}
但是,当我尝试使用HTML中的功能时,我无法获得所需的结果。 HTML代码:
<?php
$test = 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝŐŰßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿőű';
$test1 = toASCII($test);
?>
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php echo $test."<br>";
echo $test1;
?>
</body>
</html>
浏览器中的结果:
ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝŐŰßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿőű
uuuuuuuYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYuusaaaaaaaceeeeiiiionoooooouuuuyyuu
为什么某些字符显示为u
而不是所需字符的任何想法?
注意:我宁愿避免使用setlocale
,因为它需要对代码进行其他更改。
答案 0 :(得分:0)
当你使用带有三个参数的strtr()时,它使用字节而不是多字节字符(参见http://php.net/manual/en/function.strtr.php#111270)。相反,你必须给出一个包含精确映射的数组。
这将是您案件的解决方案:
<?php
function mbStringToArray( $str ) {
return preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
}
function toASCII( $str ) {
$map = array_combine(
mbStringToArray('ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝŐŰßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿőű'),
mbStringToArray('SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYOUsaaaaaaaceeeeiiiionoooooouuuuyyou')
);
return strtr($str,$map);
}
$test = 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝŐŰßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿőű';
$test1 = toASCII($test);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
echo $test."<br>";
echo $test1;
?>
</body>
</html>
输出:
ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝŐŰßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿőű
SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYOUsaaaaaaaceeeeiiiionoooooouuuuyyou