查詢方法:1、使用stripos(),查詢字符串首次出現(xiàn)的位置;2、使用strpos(),查詢字符串首次出現(xiàn)的位置;3、使用strripos(),查詢字符串最后一次出現(xiàn)的位置;4、使用strrpos(),查詢字符串最后一次出現(xiàn)的位置。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版,DELL G3電腦
在 PHP 中,可以使用以下4個(gè)函數(shù)來(lái)查找字符串。
1、使用stripos()函數(shù)
stripos() 用來(lái)查找字符串中某部分字符串首次出現(xiàn)的位置(不區(qū)分大小寫)。
語(yǔ)法如下:
int stripos ( string $haystack , string $needle [, int $offset = 0 ] )
參數(shù)說(shuō)明如下:
-
haystack:在該字符串中查找。
-
needle:needle 可以是一個(gè)單字符或者多字符的字符串。如果 needle 不是一個(gè)字符串,那么它將被轉(zhuǎn)換為整型并被視為字符順序值。
-
offset:可選的 offset 參數(shù)允許你指定從 haystack 中的哪個(gè)字符開(kāi)始查找,返回的位置數(shù)字值仍然相對(duì)于 haystack 的起始位置。
返回 needle 存在于 haystack 字符串開(kāi)始的位置(獨(dú)立于偏移量)。同時(shí)注意字符串位置起始于 0,而不是 1。如果未發(fā)現(xiàn) needle 就將返回 false。
示例如下:
<?php $findme = 'c'; $mystring1 = 'xyz'; $mystring2 = 'ABC'; $pos1 = stripos($mystring1, $findme); $pos2 = stripos($mystring2, $findme); var_dump($pos1); var_dump($pos2); ?>
執(zhí)行結(jié)果為:
bool(false) int(2)
2、使用strpos()函數(shù)
strpos() 用來(lái)查找字符串首次出現(xiàn)的位置。
語(yǔ)法如下:
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
strpos() 和 strrpos()、strripos() 不一樣,strpos 的偏移量不能是負(fù)數(shù)。
示例如下:
<?php $findme = 'c'; $findme1 = 'C'; $mystring = 'ABCabc'; $pos1 = strpos($mystring, $findme); $pos2 = strpos($mystring, $findme1); var_dump($pos1); var_dump($pos2); ?>
上述代碼的執(zhí)行結(jié)果為:
int(5)int(2)
3、使用strripos()函數(shù)
strripos() 用來(lái)計(jì)算指定字符串在目標(biāo)字符串中最后一次出現(xiàn)的位置(不區(qū)分大小寫)。
語(yǔ)法如下:
int strripos ( string $haystack , string $needle [, int $offset = 0 ] )
負(fù)數(shù)偏移量將使得查找從字符串的起始位置開(kāi)始,到 offset 位置為止。
示例如下:
<?php $findme = 'c'; $findme1 = 'C'; $mystring = 'ABCabcabcABC'; $pos1 = strripos($mystring, $findme); $pos2 = strripos($mystring, $findme1); var_dump($pos1); var_dump($pos2); ?>
上述代碼的執(zhí)行結(jié)果為:
int(11)int(11)
4、使用strrpos()函數(shù)
strrpos() 用來(lái)計(jì)算指定字符串在目標(biāo)字符串中最后一次出現(xiàn)的位置.
語(yǔ)法如下:
int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )
如果是負(fù)數(shù)的偏移量,將會(huì)導(dǎo)致查找在字符串結(jié)尾處開(kāi)始的計(jì)數(shù)位置處結(jié)束。
示例如下:
<?php $findme = 'c'; $findme1 = 'C'; $mystring = 'ABCabcabcABC'; $pos1 = strrpos($mystring, $findme); $pos2 = strrpos($mystring, $findme1); $pos3 = strrpos($mystring, $findme1,-5); var_dump($pos1); var_dump($pos2); var_dump($pos3); ?>
上述代碼的執(zhí)行結(jié)果為:
int(8)int(11)int(2)
推薦學(xué)習(xí):《PHP視頻教程》