substr_compare()函數(shù)用于從指定的開始位置比較兩個字符串。
substr_compare(string1,string2,startpos,length,case)
substr_compare() 從偏移位置 startpos 開始比較 string1 與 string2,比較長度為 length 個字符。
如果 string1 從偏移位置 startpos 起的子字符串小于 string2,則返回小于 0 的數(shù);如果大于 string2,則返回大于 0 的數(shù);如果二者相等,則返回 0。如果 startpos 大于等于 string1 的長度或 length 被設(shè)置為小于 1 的值( PHP 5.5.11 更早版本),substr_compare() 將打印出一條警告信息并且返回 FALSE。
| 序號 | 參數(shù)與說明 |
|---|---|
| 1 | string1 必需。第一個字符串 |
| 2 | string2 必需。第二個字符串 |
| 3 | startpos 必需。它指定在string1中從何處開始比較字符串 |
| 4 | length 可選。指定在 string1 中參與比較的字符數(shù)。 |
| 5 | case 布爾值,默認(rèn)為FALSE, 區(qū)分大小寫。如果 case 為 TRUE,比較將不區(qū)分大小寫。 |
試試下面的實例,比較兩個字符串,當(dāng) string1 中用于比較的開始位置為 6 時::
<?php
//比較兩個字符串,當(dāng) string1 中用于比較的開始位置為 6 時
echo substr_compare("SAi RAM","RAM",6);
echo '<br>';
//不同參數(shù)比較字符串
echo substr_compare("abcde", "bc", 1, 2); // 0
echo '<br>';
echo substr_compare("abcde", "de", -2, 2); // 0
echo '<br>';
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo '<br>';
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo '<br>';
echo substr_compare("abcde", "bc", 1, 3); // 1
echo '<br>';
echo substr_compare("abcde", "cd", 1, 2); // -1
echo '<br>';
echo substr_compare("abcde", "abc", 5, 1); // warning
?>測試看看?/?輸出結(jié)果
-5 0 0 0 0 1 -1 PHP Warning: substr_compare(): The start position cannot exceed initial string....