一、strripos概述
strripos是PHP中的一個字元串函數,其作用是在一個字元串中查找另一個字元串最後一次出現的位置,並返回其位置。
//示例1
$str = "Hello world. It's a beautiful day.";
$needle = "world";
echo strripos($str, $needle); //6
//示例2
$str = "Hello world. It's a beautiful day.";
$needle = "World";
echo strripos($str, $needle); //6
與strrpos不同的是,strripos不區分大小寫,即使$needle大小寫不一致,函數依然可以找到最後一次出現的位置。
二、參數講解
strripos函數有三個參數,分別是:
1、haystack:需要在其中搜索的字元串。
2、needle:需要搜索的字元串。
3、offset(可選參數):在哪個字元位置開始搜索。如果省略,則默認從字元串的開始處搜索。
三、搜索範圍
需要注意的是,搜索範圍是整個字元串,而不僅僅是一部分。
//示例1
$str = "Hello world. It's a beautiful day.";
$needle = "world";
echo strripos($str, $needle); //6
//示例2
$str = "Hello world. It's a beautiful day.";
$needle = "It's";
echo strripos($str, $needle); //12
//示例3
$str = "Hello world.
";
$needle = ""; echo strripos($str, $needle); //0
四、函數返回值
strripos函數的返回值是一個整數,代表$needle最後一次出現在$haystack的位置。如果沒有找到,返回false。
//示例1
$str = "Hello world. It's a beautiful day.";
$needle = "day";
echo strripos($str, $needle); //22
//示例2
$str = "Hello world. It's a beautiful day.";
$needle = ",";
$pos = strripos($str, $needle);
if ($pos === false) {
echo "沒有找到。";
} else {
echo "在第{$pos}個位置找到了。";
}
//輸出:沒有找到。
五、使用限制
需要注意的是,strripos函數只適用於字元串的情況。如果需要在數組中查找,可以使用array_search函數。
//示例
$arr = array('apple', 'banana', 'orange', 'pear');
$key = array_search('Banana', $arr, true);
echo $key; //1
六、大小寫敏感與不敏感的區別
在使用strripos函數時,需要注意大小寫敏感與不敏感的區別。
如果在搜索字元串中使用大小寫不同的字元,由於strripos函數不區分大小寫,因此結果是相同的。
//示例1
$str = "Hello world. It's a beautiful day.";
$needle = "world";
echo strripos($str, $needle); //6
//示例2
$str = "Hello world. It's a beautiful day.";
$needle = "World";
echo strripos($str, $needle); //6
如果在搜索字元串和被搜索字元串中使用大小寫不同的字元,結果可能有所不同。
//示例1
$str = "Hello world. It's a beautiful day.";
$needle = "DAY";
echo strripos($str, $needle); //22
//示例2
$str = "Hello WORLD. It's a beautiful day.";
$needle = "day";
echo strripos($str, $needle); //22
七、大小寫轉換函數
如果在使用strripos函數前需要將字元串轉換為小寫或大寫,可以使用strtolower和strtoupper函數。
//示例1
$str = "Hello WORLD. It's a beautiful day.";
$needle = "day";
$pos = strripos(strtolower($str), strtolower($needle));
echo $pos; //22
//示例2
$str = "Hello WORLD. It's a beautiful day.";
$needle = "day";
$pos = strripos(strtoupper($str), strtoupper($needle));
echo $pos; //22
八、結語
以上是對strripos函數的詳細講解和示例。在使用該函數時,需要注意大小寫敏感與不敏感的區別,以及搜索範圍和返回值的特殊情況。
原創文章,作者:MZAUP,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/334459.html