PHP 字符串 strcmp()函數
字符串比較是編程和開發中最常見的任務之一。愛掏網 - it200.comstrcmp()是PHP中的一個字符串比較函數。愛掏網 - it200.com它是PHP的內建函數,它 區分大小寫 ,意味著它將大寫和小寫視為不同。愛掏網 - it200.com它用于比較兩個字符串。愛掏網 - it200.com此函數比較兩個字符串并判斷一個字符串是否大于、小于或等于另一個字符串。愛掏網 - it200.comstrcmp()函數是 二進制安全的字符串比較 。愛掏網 - it200.com
注意:strcmp()函數對大小寫敏感,同時也是二進制安全的字符串比較。愛掏網 - it200.com
strcoll(str1,str2);
參數
strcmp()函數接受兩個字符串參數,在函數體中傳遞是必需的。愛掏網 - it200.com需要傳遞的都是strcmp()函數中的必需參數。愛掏網 - it200.com下面給出了以下參數的描述。愛掏網 - it200.com
- $str1 - 它是strcmp()函數的第一個參數,用于比較。愛掏網 - it200.com
- $str2 - 它是strcmp()函數的第二個參數,用于比較。愛掏網 - it200.com
strcmp()函數返回的值
該函數根據比較隨機返回整數值。愛掏網 - it200.com
返回0 - 如果兩個字符串相等,即str1 =str2,它返回0。愛掏網 - it200.com
返回小于0 - 如果字符串1小于字符串2,即str1<str2,它返回一個負值。愛掏網 - it200.com
返回大于0 - 如果字符串1大于字符串2,即str1 >str2,它返回一個正值。愛掏網 - it200.com
注意:它計算字符串的ASCII值,然后比較兩個字符串以判斷它們是否相等、大于或小于。愛掏網 - it200.com
strcoll()和strcmp()函數的區別
strcoll()和strcmp()都是PHP的字符串比較函數,但它們在某些方面稍有不同。愛掏網 - it200.com
strcoll() 接受字節并使用區域設置轉換它們,然后比較結果,而 strcmp() 按順序逐個比較字符串的字節。愛掏網 - it200.com
示例1
<?php
str1 = "hello php";str2 = "hello php";
echo strcoll(str1,str2). " because both strings are equal. ";
echo " </br>";
echo strcoll("Hello world", "Hello"). " because the first string is greater than the second string.";
?>
輸出:
0 because both strings are equal.
6 because the first string is greater than the second string.
注意: 第二個字符串的比較返回了6的值,因為第一個字符串比第二個字符串長出6個字符,包括空格。愛掏網 - it200.com
示例2
<?php
echo strcoll("Hello world", "hello"). " because the first string is less than the second string.";
echo "</br>";
echo strcoll("hello", "Hello"). " because the first string is greater than the second string.";
?>
輸出:
-1 because the first string is less than the second string.
1 because the first string is greater than the second string.
示例3
<?php
echo strcmp("Hello ", "HELLO"). " because the first string is greater than the second string.";
echo "</br>";
echo strcmp("Hello world", "Hello world Hello"). " because the first string is less than the second string.";
?>
輸出:
1 because the first string is greater than the second string.
-6 because the first string is less than the second string.
備注: 第二個字符串比較返回-6,因為第一個字符串比第二個字符串短6個字符,包括空格。愛掏網 - it200.com
字符串1 | 字符串2 | 輸出 | 解釋 |
---|---|---|---|
Hello | Hello | 0 | 兩個字符串相同且相等。愛掏網 - it200.com |
Hello | hello | -1 | 字符串1 < 字符串2,因為 H 的 ASCII 值是 72,h 的 ASCII 值是 104,所以 H < h。愛掏網 - it200.com它區分大小寫。愛掏網 - it200.com |
hello | Hello | 1 | 字符串1 > 字符串2,因為 H 的 ASCII 值是 72,h 的 ASCII 值是 104,所以 H < h。愛掏網 - it200.com |
Hello PHP | Hello | 4 | 字符串1 > 字符串2,因為字符串1比字符串2多了6個字符,包括空格。愛掏網 - it200.com |
hello | Hello PHP | 1 | 字符串1 > 字符串2,因為 H 的 ASCII 值是 72,h 的 ASCII 值是 104,所以 H < h。愛掏網 - it200.com |
Hello | Hello PHP | -4 | 字符串1 < 字符串2,因為字符串1比字符串2少了4個字符,包括空格。愛掏網 - it200.com |