PHP 字符串 strncasecmp()函數
strncasecmp()是PHP的一個內置函數,它是不區分大小寫的。愛掏網 - it200.com它用于比較兩個字符串的前n個字符。愛掏網 - it200.com此函數類似于strcasecmp()函數,但有一個區別。愛掏網 - it200.com在strncasecmp()中,我們可以指定要比較的字符串的字符數,而strcasecmp()不包含長度參數。愛掏網 - it200.comstrncasecmp()是一個二進制安全的函數。愛掏網 - it200.com
注意: strncasecmp()是一個不區分大小寫和二進制安全的函數。愛掏網 - it200.com
strncasecmp()函數的語法如下:
strncasecmp( string1,string2, $length)
所有三個參數在此函數中都是必需的。愛掏網 - it200.com它在比較后返回一個整數值。愛掏網 - it200.com
參數
$string1 (必需): 這是用于比較的第一個字符串。愛掏網 - it200.com它是一個必需的參數。愛掏網 - it200.com
$string2 (必需): 這是用于比較的第二個必需字符串。愛掏網 - it200.com
$length: 這是此函數的最后和必需參數,指定要用于比較的字符串的長度。愛掏網 - it200.com
返回值
返回值 | 描述 |
---|---|
返回 < 0 | 如果string1小于string2,即$string < $string2 。愛掏網 - it200.com |
返回 0 | 如果兩個字符串相等。愛掏網 - it200.com |
返回 > 0 | 如果string1大于string2,即$string > $string2 。愛掏網 - it200.com |
示例
下面給出了一些示例,您可以從中學習在程序中對此函數的實際應用。愛掏網 - it200.com
Input:
string1 = "Hello World",string2 = "HELLO ", len = 5; //case-insensitive
Output: 0
Input:string1 = "Hello World ", string2 = "Hello ",len = 11;
Output: 6
Input:
string1 = "Hello PHP! ",string2 = "PHP", len = 9
Output: -8
Input:string1 = "PHP! ", string2 = "Hello PHP",len = 9
Output: 8
Input:
string1 = "Hello ",string2 = "Hello PHP", $len = 9
Output: -4
以下是一些詳細的示例 –
示例1
這是strncasecmp()的簡單示例,它展示了它是不區分大小寫的函數。愛掏網 - it200.com
<?php
string1 = "Welcome to javaTpoint";string2 = "WELCOME"; //case-insensitive
len = 7;
//Both strings are equal
echo strncasecmp(string1, string2,len);
?>
輸出結果:
0
示例2
<?php
string1 = "Welcome to javaTpoint";string2 = "Welcome";
len = 20;
//string1 is greater than string2
echo strncasecmp(string1, string2,len);
?>
輸出:
在這個示例中,函數返回了13,因為string1大于string2。愛掏網 - it200.com
13
示例3
<?php
string1 = "Welcome";string2 = "Welcome to javaTpoint";
len = 20;
//string1 is less than string2
echo strncasecmp(string1, string2,len);
?>
輸出:
在這個示例中,函數返回了-13,因為string1小于string2。愛掏網 - it200.com
-13
示例4
<?php
string1 = "Welcome to javaTpoint";string2 = "Hello";
len = 20;
//string1 is greater than string2 and also not same
echo strncasecmp(string1, string2,len);
?>
輸出:
15
示例 5
<?php
string1 = "Hello World";string2 = "Hello earth";
len = 11; //string1 is not same as string2.
echo strncasecmp(string1, string2,len);
?>
輸出:
在上面的示例中,這個函數返回了18,因為string2大于string1。愛掏網 - it200.come的ASCII值(101)大于W(87)。愛掏網 - it200.com
18
示例6
<?php
string1 = "Good afternoon";string2 = "Good afternoor";
len = 14;
//string2 has a character (r) with higher ASCII value, so, output would be <0
echo strncasecmp(string1, string2,len);
?>
輸出:
在此示例中,函數返回-4,因為string1小于string2。愛掏網 - it200.com在string2中,下午后面的n被替換為r。愛掏網 - it200.comr的ASCII值(114)大于n(110),因此較小。愛掏網 - it200.com
-4
示例7
如果我們在函數中不提供比較的長度,那么將會顯示錯誤。愛掏網 - it200.com
<?php
string1 = "Good afternoon";string2 = "Good afternoor";
echo strncasecmp(string1,string2);
?>
輸出:
我們可以看到輸出結果中出現了一個警告,即函數預期需要三個參數,而程序中只傳遞了兩個參數。愛掏網 - it200.com