简体   繁体   中英

PHP setlocale on OSX/FreeBSD doesn't work

I got problem on FreeBSD/OSX with sorting results by locale. Here is code (which works OK on 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);
?>

I checked on OSX which locale I got:

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

and then by files:

$ 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

The interesting thing is, LC_COLLATE in OSX for every language point to the same file. Sys info:

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

Any idea how sort it right using locale?

Use Collator instead (Linux/Win/Mac compatible):

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM