gpt4 book ai didi

php - PHP 和 MySQL 中的土耳其字符问题

转载 作者:行者123 更新时间:2023-11-29 05:19:59 26 4
gpt4 key购买 nike

我正在尝试计算 MySQL 数据库中土耳其字母表中所有字母的出现次数。

当我尝试像这样计算字母“a”时,我得到了正确的结果:

while($nt=mysql_fetch_array($rt))
{
$mystring = $nt["word"];

for($i = 0; $i < strlen($mystring) ; $i++)
{
if($mystring[$i] == 'a')
{
$a++;
}
}
}

当我用“ç”替换“a”时,我得到零。我已经添加了这段代码:

$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("database unavailable");
mysql_set_charset('utf8', $bd);

如何修复土耳其语字符的代码?谢谢。

最佳答案

在 UTF-8 中,ç 被编码为两个字节 (C3 A7),因此逐字节比较将不起作用。考虑 substr_count:

$s = "abçdeç";
print substr_count($s, 'ç'); // 2

或者使用像这样的 unicode-aware 函数:

function utf8_char_count($s) {
$count = [];
preg_match_all('~.~u', $s, $m);
foreach($m[0] as $c)
$count[$c] = isset($count[$c]) ? $count[$c] + 1 : 1;
return $count;
}

print_r(utf8_char_count('çAüθç')); // [ç] => 2 [A] => 1 [ü] => 1 [θ] => 1

这假定您的字符串实际上是 UTF-8,如果不是这种情况(提示:var_dump(rawurlencode($str))),请检查您的数据库和连接设置(请参阅链接线程)。

关于php - PHP 和 MySQL 中的土耳其字符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27245453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com