Php/docs/function.substr-compare

提供:Dev Guides
< Php
移動先:案内検索

substr_compare

(PHP 5, PHP 7)

substr_compare指定した位置から指定した長さの 2 つの文字列について、バイナリ対応で比較する


説明

substr_compare ( string $haystack , string $needle , int $offset [, int|null $length = null [, bool $case_insensitive = false ]] ) : int

substr_compare() は、haystackoffset 文字目以降の最大 length 文字を、needle と比較します。


パラメータ

haystack
比較したい最初の文字列。
needle
比較したい二番目の文字列。
offset
比較を開始する位置。 負の値を指定した場合は、文字列の最後から数えます。
length
比較する長さ。デフォルト値は、 haystack の長さから offset を引いたものと needle の長さのうち、長いほうです。
case_insensitive
case_insensitivetrue の場合、 大文字小文字を区別せずに比較します。


返り値

haystackoffset 以降が needle より小さい場合に負の数、 needle より大きい場合に正の数、 等しい場合に 0 を返します。 offsethaystack と等しい (PHP 7.2.18, 7.3.5 より前のバージョン) か、 haystack より長い場合、 もしくは length が設定されていて0未満である場合、 substr_compare() は警告を表示して false を返します。


変更履歴

バージョン 説明
8.0.0 length は、nullable になりました。
7.2.18, 7.3.5 offset の値は、

haystack の長さと等しくても問題なくなりました。


例1 substr_compare() の例

<?phpecho substr_compare("abcde", "bc", 1, 2); // 0echo substr_compare("abcde", "de", -2, 2); // 0echo substr_compare("abcde", "bcg", 1, 2); // 0echo substr_compare("abcde", "BC", 1, 2, true); // 0echo substr_compare("abcde", "bc", 1, 3); // 1echo substr_compare("abcde", "cd", 1, 2); // -1echo substr_compare("abcde", "abc", 5, 1); // 警告?>

参考

  • strncmp() - 最初の n 文字についてバイナリセーフな文字列比較を行う