PHP setlocale() not working for ctype_alpha check

2019-08-04 07:02发布

I run this php code:

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>";

and get this output:

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?

I expected that after the call to setlocale (LC_ALL, 'de_DE.utf8') ctype_alpha would accept german characters like äöüß, as written in the documentation: "Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise." but it doesn't. What am i doing wrong here?

PHP Version is : 5.3.10-1ubuntu3.8

1条回答
姐就是有狂的资本
2楼-- · 2019-08-04 07:24

It's not documented but, since you are using utf8 version of the locale, if your file encoding is also UTF-8 you'll have to use utf8_decode() to make it work:

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)

Tested with PHP 5.4.17-cli on a OS X Mavericks machine with UTF-8, ISO-8859-1, KOI8-U and Windows 1252 file encodings.

查看更多
登录 后发表回答