PL *_*det 15 php string comparison utf-8
我想比较两个字符串让我们说Émilie和Zoey.好的'E'出现在'Z'之前,但在ASCII图表Z之前出现É所以正常if ( str1 > str2 )无效.
我试过if (strcmp(str1,str2) > 0)还是不行.所以我正在寻找一种将字符串与UTF-8字符进行比较的本地方式.
tha*_*tah 13
重要
这个答案适用于无法运行/安装'intl'扩展的情况,只能通过将重音字符替换为非重音字符来对字符串进行排序.要根据特定区域设置对重音字符进行排序,使用Collator是一种更好的方法 - 有关详细信息,请参阅此问题的其他答案.
在PHP 5.2中按非重音字符排序
您可以尝试使用iconv()和// TRANSLIT选项将两个字符串转换为ASCII以删除重音字符;
$str1 = iconv('utf-8', 'ascii//TRANSLIT', $str1);
Run Code Online (Sandbox Code Playgroud)
然后进行比较
请参阅此处的文档:
http://www.php.net/manual/en/function.iconv.php
[更新,回应@ Esailija的评论]我忽略了// TRANSLIT以意想不到的方式翻译重音字符的问题.这个问题在这个问题中被提到:php iconv translit用于删除重音:不作为例外工作?
为了使'iconv()'方法有效,我在下面添加了一个代码示例,它使用preg_replace()从结果字符串中去除所有非单词字符.
<?php
setLocale(LC_ALL, 'fr_FR');
$names = array(
'Zoey and another (word) ',
'Émilie and another word',
'Amber',
);
$converted = array();
foreach($names as $name) {
$converted[] = preg_replace('#[^\w\s]+#', '', iconv('UTF-8', 'ASCII//TRANSLIT', $name));
}
sort($converted);
echo '<pre>'; print_r($converted);
// Array
// (
// [0] => Amber
// [1] => Emilie and another word
// [2] => Zoey and another word
// )
Run Code Online (Sandbox Code Playgroud)
Fab*_*ler 11
没有本地方法可以做到这一点,但是PECL扩展:http://php.net/manual/de/class.collator.php
$c = new Collator('fr_FR');
if ($c->compare('Émily', 'Zoey') < 0) { echo 'Émily < Zoey'; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17013 次 |
| 最近记录: |