Collator::compare
collator_compare
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
Collator::compare -- collator_compare — Compare two Unicode strings
说明
面向对象风格
$string1
, string $string2
): int|false过程化风格
Compare two Unicode strings according to collation rules.
参数
-
object
-
Collator object.
-
string1
-
The first string to compare.
-
string2
-
The second string to compare.
返回值
Return comparison result:
-
1 if
string1
is greater thanstring2
; -
0 if
string1
is equal tostring2
; -
-1 if
string1
is less thanstring2
.
false
on failure.
范例
示例 #1 collator_compare() example
<?php
$s1 = 'Hello';
$s2 = 'hello';
$coll = collator_create( 'en_US' );
$res = collator_compare( $coll, $s1, $s2 );
if ($res === false) {
echo collator_get_error_message( $coll );
} else if( $res > 0 ) {
echo "s1 is greater than s2\n";
} else if( $res < 0 ) {
echo "s1 is less than s2\n";
} else {
echo "s1 is equal to s2\n";
}
?>
以上例程会输出:
s1 is greater than s2
示例 #2 Comparing strings without diacritics or case-sensitivity
<?php
$c = new Collator( 'en' );
$c->setStrength( Collator::PRIMARY );
if ( $c->compare( 'Séan', 'Sean' ) == 0 )
{
echo "The same\n";
}
以上例程会输出:
The same
This example instructs the collator to compare with only taking the base characters into account. The documentation for Collator->setStrength() explains the different strengths.

User Contributed Notes 1 note
The Collator class with method compare does what the non existing mb_strcmp, mb_strcasecmp, mb_strnatcmp and mb_strnatcasecmp would do for multibyte strings (UTF8) - but better! :-)
For "case": the Collator is case insensitive due to Collator::CASE_FIRST defaults to Collator::OFF, but can be changed with method setAttribute.
For "nat" (natural sort order for numbers): use method setAttribute with Collator::NUMERIC_COLLATION and Collator:ON to enable.