PHP的strtolower()和strtoupper()函数为什么在非中文系统的服务器下可能会导致汉字乱码?请写两个替代的函数实现兼容Unicode文字的字符串大小写转换。
<?php
/**
* PHP的strtolower()和strtoupper()函数为什么在非中文系统的服务器下可能会导致汉字乱码
* 解决思路是英文字符通过ascii码表去转换,中文字符忽略
*/
/**
* 字符串转大写
* @param $str
* @return false|mixed|string
*/
function stringToUpper($str)
{
if (!is_string($str)) {
return false;
}
$chars = str_split($str, 1);
$resultStr = '';
foreach ($chars as $char)
{
$asciiChar = ord($char);
if ($asciiChar >= ord('a') && $asciiChar <= ord('z')) {
$asciiChar += ord('A') - ord('a');
$char = chr($asciiChar);
}
$resultStr .= $char;
}
return $resultStr;
}
/**
* 字符串转小写
* @param $str
* @return false|string
*/
function stringToLower($str)
{
if (!is_string($str)) {
return false;
}
$chars = str_split($str, 1);
$resultStr = '';
foreach ($chars as $char)
{
$asciiChar = ord($char);
if ($asciiChar >= ord('A') && $asciiChar <= ord('Z')) {
$asciiChar -= ord('A') - ord('a');
$char = chr($asciiChar);
}
$resultStr .= $char;
}
return $resultStr;
}
$str = 'Abc中文';
echo stringToUpper($str);
echo stringToLower($str);