PHP 8.3.4 Released!

Collator::compare

collator_compare

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::compare -- collator_compareふたつの Unicode 文字列を比較する

説明

オブジェクト指向型

public Collator::compare(string $string1, string $string2): int|false

手続き型

collator_compare(Collator $object, string $string1, string $string2): int|false

ふたつの Unicode 文字列を、比較規則にもとづいて比較します。

パラメータ

object

Collator オブジェクト。

string1

最初の文字列。

string2

2 番目の文字列。

戻り値

比較結果を返します。

  • string1string2 より 大きい ときは 1

  • string1string2等しい ときは 0

  • string1string2 より 小さい ときは -1

エラー時には false を返します。

警告

この関数は論理値 false を返す可能性がありますが、false として評価される値を返す可能性もあります。 詳細については 論理値の セクションを参照してください。この関数の返り値を調べるには ===演算子 を 使用してください。

例1 collator_compare() の例

<?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 ダイアクリティカルマークや、大文字小文字の区別を無視して比較する

<?php
$c
= new Collator( 'en' );
$c->setStrength( Collator::PRIMARY );
if (
$c->compare( 'Séan', 'Sean' ) == 0 )
{
echo
"The same\n";
}

上の例の出力は以下となります。


The same

この例は、collator に基本的な文字のみを考慮するように指示します。 Collator->setStrength() のドキュメントは、照合強度の違いについて説明しています。

参考

add a note

User Contributed Notes 1 note

up
3
erik at eldata dot se
3 years ago
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.
To Top