PHP | Функция strncasecmp ()
Функция strncasecmp () является встроенной функцией PHP и используется для сравнения двух заданных строк. Регистр не учитывается. Эта функция похожа на strcasecmp (), единственное отличие заключается в возможности указать количество символов, которые будут использоваться в каждой строке для сравнения.
Синтаксис:
strncasecmp ($ строка1, $ строка2, $ длина)
Параметры: эта функция принимает два параметра, как показано в синтаксисе выше и описаны ниже:
- $ string1, $ string2: эти параметры определяют строки для сравнения.
- $ length: указывает количество символов в каждой строке, которые будут использоваться при сравнении. Этот параметр обязателен
Возвращаемое значение: эта функция возвращает целое число в соответствии с условиями, описанными ниже:
- strncasecmp () возвращает 0 - если две строки равны.
- strncasecmp () возвращает <0 - если строка1 меньше строки2
- strncasecmp () возвращает> 0 - если строка1 больше, чем строка2
Примеры:
Input : string1 = "Hello", string2 = "hEllo", length = 6 Output : 0 Input : string1 = "Geeks", string2 = "Gfg", length = 3 Output : -1 Input : string1 = "Nerd", string2 = "Geeks", length = 4 Output : 7
Ниже приведены программы, иллюстрирующие функцию strncasecmp () в PHP:
Program 1: When the two strings are identical:
<?php $str1 = "Geeks for Geeks ";$str2 = "Geeks for Geeks "; // Both the strings are equal$test=strncasecmp($str1, $str2, 16 ); echo "$test"; ?> |
Выход :
0
Program 2 : When first string greater than the second string:
<?php // Input strings$str1 = "Geeks for Geeks ";$str2 = "Geeks for "; $test=strncasecmp($str1, $str2, 16 ); // In this case the second string is smallerecho "$test"; ?> |
Выход:
6
Program 3: First string is smaller than the second string:
<?php // Input Strings$str1 = "Geeks for ";$str2 = "Geeks for Geeks "; $test=strncasecmp($str1, $str2, 16 ); // In this case the first string is smallerecho "$test"; ?> |
Выход:
-6
Program 4: This program illustrates the case-insensitivity of the function:
<?php // Input Strings$str1 = "GEEKS FOR GEEKS ";$str2 = "Geeks for Geeks "; // Both the strings are equal$test=strncasecmp($str1, $str2, 16 ); echo "$test"; ?> |
Выход:
0
Program 5: Two strings are of equal length but contain a different character. In such a case the difference between ASCII value of the two characters is displayed. The function returns a positive value if the character in string1 has a greater ASCII value and negative if the character in string2 has a greater ASCII value.
<?php // Input Strings $str1 = "Good";$str2 = "Goon"; $test1 = strncasecmp($str1, $str2, 4 ); // Second string has a character // with higher ASCII valueecho "$test1"; echo "
"; $test2 = strncasecmp($str2, $str1, 4 ); // First string has a character // with higher ASCII valueecho "$test2"; ?> |
Выход:
-10 10
Ссылка :
http://php.net/manual/en/function.strncasecmp.php