【问题标题】:PHP setlocale on OSX/FreeBSD doesn't workOSX/FreeBSD 上的 PHP setlocale 不起作用
【发布时间】:2018-04-19 20:35:20
【问题描述】:

我在 FreeBSD/OSX 上遇到了按区域设置排序结果的问题。这是代码(在 linux 上运行正常)

<?php
header('Content-Type: text/html; charset=utf-8');
echo "<pre>"; 
setlocale(LC_ALL, 'cs_CZ.UTF-8', 'Czech');
echo "Set locale: ". setlocale(LC_ALL, 0) . "\n";
$countries = array(
    'Bulharsko',
    'Česko',
    'Polsko',
    'Čína'
);

sort($countries, SORT_LOCALE_STRING);
print_r($countries);
?>

我在 OSX 上查看了我得到的语言环境:

$locale -a
...
cs_CZ
cs_CZ.ISO8859-2
cs_CZ.UTF-8
...

然后按文件:

$ pwd
/usr/share/locale/cs_CZ.UTF-8
$ ls -la
total 24
drwxr-xr-x    8 root  wheel   272 Oct 23 18:07 ./
drwxr-xr-x  226 root  wheel  7684 Oct 23 18:07 ../
lrwxr-xr-x    1 root  wheel    28 Oct 23 18:06 LC_COLLATE@ -> ../la_LN.US-ASCII/LC_COLLATE
lrwxr-xr-x    1 root  wheel    17 Oct 23 18:06 LC_CTYPE@ -> ../UTF-8/LC_CTYPE
drwxr-xr-x    3 root  wheel   102 Oct 23 18:07 LC_MESSAGES/
-r--r--r--    1 root  wheel    36 Oct 23 18:06 LC_MONETARY
lrwxr-xr-x    1 root  wheel    29 Oct 23 18:06 LC_NUMERIC@ -> ../cs_CZ.ISO8859-2/LC_NUMERIC
-r--r--r--    1 root  wheel   397 Oct 23 18:06 LC_TIME

有趣的是,OSX 中的 LC_COLLATE 对于每种语言都指向同一个文件。系统信息:

PHP 5.4.23 (cli) (built: Dec 16 2013 00:36:15) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

(OSX 10.9.1): Darwin MBP.local 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE_X86_64 x86_64

知道如何使用语言环境对其进行正确排序吗?

【问题讨论】:

  • 你有什么发现吗?在使用 php 5.5、5.6、7.0 的 FreeBSD 10.2 中遇到了同样的问题。
  • 你应该使用 intl 扩展(Collat​​or 类),这样更可靠。

标签: php macos sorting locale freebsd


【解决方案1】:

改用 Collat​​or(Linux/Win/Mac 兼容):

$usedLocale = setlocale (LC_COLLATE, 'cs_CZ.utf8', 'cs_CZ.UTF-8', 'Czech', 'cs_CZ', 'cs');
$collator = new Collator($usedLocale);
$collator->asort($countries, SORT_LOCALE_STRING);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 2015-03-31
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多