【问题标题】:PHP setlocale() not working for ctype_alpha checkPHP setlocale() 不适用于 ctype_alpha 检查
【发布时间】:2013-11-24 15:33:49
【问题描述】:

我运行这个 php 代码:

echo "<br>system locales: ".system('locale -a')."<br><br>";
echo "current locales: ".setlocale(LC_ALL, 0)."<br><br>";
var_dump(setlocale (LC_ALL, 'de_DE.utf8'));
echo "current locales: ".setlocale(LC_ALL, 0)."<br><br>";
echo "accepting german characters?: ".ctype_alpha("äüöß")."<br><br>";
echo "accepting characters in general?: ".ctype_alpha("test")."<br><br>";
echo "rejecting numbers?: ".ctype_alpha("tes2t")."<br><br>";

并得到这个输出:

C C.UTF-8 POSIX de_DE.utf8
system locales: de_DE.utf8

current locales: C

string(10) "de_DE.utf8" current locales: de_DE.utf8

accepting german characters?:

accepting characters in general?: 1

rejecting numbers?

我希望在调用 setlocale (LC_ALL, 'de_DE.utf8') ctype_alpha 后会接受像 äöüß 这样的德语字符,如文档中所写:"Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise." 但事实并非如此。 我在这里做错了什么?

PHP 版本为:5.3.10-1ubuntu3.8

【问题讨论】:

  • äüöß 字符串的编码是什么?也就是说,源代码文件保存为什么编码?

标签: php ubuntu character-encoding locale


【解决方案1】:

没有记录,但是由于您使用的是 utf8 版本的语言环境,如果您的文件编码也是 UTF-8,则必须使用 utf8_decode() 才能使其工作:

setlocale(LC_ALL, 'de_DE.utf8');
// Assuming your file encoding is also UTF-8
var_dump(ctype_alpha(utf8_decode('äüöß'))); // bool(true)
// Assuming your file encoding is anything else
var_dump(ctype_alpha('äüöß')); // bool(true)

在具有 UTF-8、ISO-8859-1、KOI8-U 和 Windows 1252 文件编码的 OS X Mavericks 机器上使用 PHP 5.4.17-cli 进行测试。

【讨论】:

  • 我尝试了你的建议,但是: echo "accepting utf8 decoded German characters?: ".ctype_alpha(utf8_decode('äüöß'))."

    ";返回“接受 utf8 解码的德语字符?:” :-(
  • 如果有的话,utf8_encode 就是你想要的。但您可能只想以正确的编码 (UTF-8) 保存您的源代码。
  • @Samy 我已经尝试过使用其他文件编码并相应地更新了我的答案,以了解对我有用的内容。
  • 亲爱的投反对票的人:先自己试试,再投反对票。你的论据是什么?您是否曾经在相同条件下尝试过我的答案?如果不是,你为什么投反对票?为什么你不能自己回答这个问题? :)
  • @PauloFreitas 我赞成你的回答,因为我认为它与不在 utf8 环境中工作的人有关。
猜你喜欢
  • 2014-11-06
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
相关资源
最近更新 更多