字符串比较:与 PHP 中 JavaScript 的 localeCompare 相同的东西? [英] String comparison: something identical of JavaScript's localeCompare in PHP?

查看:26
本文介绍了字符串比较:与 PHP 中 JavaScript 的 localeCompare 相同的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么解决方案可以让 PHP 中的字符串比较函数与 JavaScript 的 string.localeCompare() 相同?

Is there any solution to have a string comparison function in PHP identical to JavaScript's string.localeCompare()?

我的目标是制作一个哈希器,它可以应用于 PHP 和 JS 中的简单对象.属性排序可以基于这个问题来解决:按属性值对 JavaScript 对象进行排序

My goal is to make a hasher that can be applied over simple objects in PHP and in JS as well. The property ordering can be solved based on this question: Sorting JavaScript Object by property value

我制作了一个属性键和值元组的列表,并按键对列表进行排序.(请注意,这也可以递归地工作.)但我有点害怕字符串表示和语言环境,因为它们可能很棘手.如果属性键包含一些花哨的字符,那么 PHP 和 JS 端的排序可能不同,从而导致不同的哈希值.

I make a list of property key and value tuplets and I order the list by the keys. (Note that this can work recursively too.) But I'm a bit afraid of string representations and locales, that they might be tricky. If the property keys contain some fancy characters then the sorting may be different in PHP and JS side, resulting in different hashes.

在 PHP 中尝试以下,并在 JS 中进行类似的比较.

Try the following in PHP, and make a similar comparison in JS.

echo strcmp('e', 'é')."\n";
echo strcmp('e', 'ě')."\n";
echo strcmp('é', 'ě')."\n";
echo strcmp('e', 'f')."\n";
echo strcmp('é', 'f')."\n"; // This will differ
echo strcmp('ě', 'f')."\n"; // This will differ

主要问题:如何在 PHP 和 JS 中执行相同的字符串比较?

Main question: how can I perform identical string comparison in PHP and JS?

附带问题:PHP 和 JS 中对象散列的其他想法?

Side question: Other ideas for object hashing in PHP and JS?

推荐答案

看看 intl 扩展.

例如

<?php
// the intl extensions works on unicode strings
// so this is my way to ensure this example uses utf-8
define('LATIN_SMALL_LETTER_E_WITH_ACUTE', chr(0xc3).chr(0xa9));
define('LATIN_SMALL_LETTER_E_WITH_CARON', chr(0xc4).chr(0x9b));
ini_set('default_charset', 'utf-8');
$chars = [
    'e',
    LATIN_SMALL_LETTER_E_WITH_ACUTE,
    LATIN_SMALL_LETTER_E_WITH_CARON,
    'f'
];

$col = Collator::create(null);  // the default rules will do in this case..
$col->setStrength(Collator::PRIMARY); // only compare base characters; not accents, lower/upper-case, ...

for($i=0; $i<count($chars)-1; $i++) {
    for($j=$i; $j<count($chars); $j++) {
        echo $chars[$i], ' ', $chars[$j], ' ',
            $col->compare($chars[$i], $chars[$j]),
            "<br />\r\n";
    }
}

印刷品

e e 0
e é 0
e ě 0
e f -1
é é 0
é ě 0
é f -1
ě ě 0
ě f -1

这篇关于字符串比较:与 PHP 中 JavaScript 的 localeCompare 相同的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆