Skip to content Skip to sidebar Skip to footer

String Comparison: Something Identical Of Javascript's Localecompare In Php?

Is there any solution to have a string comparison function in PHP identical to JavaScript's string.localeCompare()? My goal is to make a hasher that can be applied over simple obje

Solution 1:

Take a look at the intl extension.

e.g.

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

prints

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

Solution 2:

you have strcmp

int strcmp ( string$str1 , string$str2 )

Returns 0 if the same string < 0 if smaller and > 0 if bigger

Post a Comment for "String Comparison: Something Identical Of Javascript's Localecompare In Php?"