PHP的strtolower()和strtoupper()函数在安装非中文系统的服务器下可能会导致将汉字转换为乱码,请写两个替代的函数实现兼容Unicode文字的字符串大小写转换

面试遇到的题:

PHP的strtolower()和strtoupper()函数在安装非中文系统的服务器下可能会导致将汉字转换为乱码,请写两个自定义函数实现兼容带 Unicode 文字的字符串大小写转换代替 strtolower() 、 strtoupper();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php

/**
ascii 码:A (65) Z(90) a(97) z(122)
a A 相差 32
*/
function user_mb_strtolower(string $str)
{
$strarr = str_split($str, 1);
$res = '';
foreach($strarr as $row){
$charascii = ord($row);
if($charascii >= 65 && $charascii < 97){
$charascii += 32;
}

$res .= chr($charascii);
}

return $res;
}

echo user_mb_strtolower("。你好");

function user_mb_strtoupper(string $str)
{
$strarr = str_split($str, 1);
$res = '';
foreach($strarr as $row){
$charascii = ord($row);
if($charascii >= 97 && $charascii < 123){
$charascii -= 32;
}

$res .= chr($charascii);
}

return $res;
}

echo user_mb_strtoupper("a你好");

php mbstring 库

  • mb_strtolower(字符串)
  • mb_strtoupper(字符串)
  • mb_convert_case(字符串,模式,字符集): 转换大、小写