本教程操作環(huán)境:windows7系統(tǒng)、PHP8.1版、DELL G3電腦
php檢測字符串中是否包含另一個字符串
方法1:利用strpos()函數(shù)檢測
(資料圖片)
strpos() 函數(shù)可以查找字符串在另一字符串中第一次出現(xiàn)的位置(區(qū)分大小寫)。
如果指定字符存在,則返回第一次出現(xiàn)的位置;如果沒有找到,則返回 FALSE。
注釋: 字符串位置從 0 開始,不是從 1 開始。
示例:
<?phpheader("content-type:text/html;charset=utf-8"); $findme1 = "y";$findme2 = "Y";$mystring = "xyz";$pos1 = strpos($mystring, $findme1);$pos2 = strpos($mystring, $findme2);var_dump($pos1);var_dump($pos2);if($pos1){echo $mystring." 中包含指定字符 $findme1 <br>";}else{echo $mystring." 中不包含指定字符 $findme1 <br>";}if($pos2){echo $mystring." 包含指定字符 $findme2 <br>";}else{echo $mystring." 不包含指定字符 $findme2 <br>";}?>方法2:利用strrpos()函數(shù)檢測
strrpos() 函數(shù)可以查找字符串在另一字符串中最后一次出現(xiàn)的位置(區(qū)分大小寫)。
如果指定字符存在,則返回最后一次出現(xiàn)的位置;如果沒有找到,則返回 FALSE。
示例:
<?phpheader("content-type:text/html;charset=utf-8"); $findme1 = "C";$findme2 = "c";$mystring = "ABC";$pos1 = strrpos($mystring, $findme1);$pos2 = strrpos($mystring, $findme2);var_dump($pos1);var_dump($pos2);if($pos1){echo $mystring." 中包含指定字符 $findme1 <br>";}else{echo $mystring." 中不包含指定字符 $findme1 <br>";}if($pos2){echo $mystring." 包含指定字符 $findme2 <br>";}else{echo $mystring." 不包含指定字符 $findme2 <br>";}?>方法3:使用stripos()函數(shù)
stripos()函數(shù)可以查找字符串在另一字符串中第一次出現(xiàn)的位置(不區(qū)分大小寫)。
如果指定字符存在,則返回第一次出現(xiàn)的位置;如果沒有找到,則返回 FALSE。
<?phpheader("content-type:text/html;charset=utf-8"); $findme1 = "y";$findme2 = "Y";$mystring = "xyz";$pos1 = stripos($mystring, $findme1);$pos2 = stripos($mystring, $findme2);var_dump($pos1);var_dump($pos2);if($pos1){echo $mystring." 中包含指定字符 $findme1 <br>";}else{echo $mystring." 中不包含指定字符 $findme1 <br>";}if($pos2){echo $mystring." 包含指定字符 $findme2 <br>";}else{echo $mystring." 不包含指定字符 $findme2 <br>";}?>方法4:使用strripos()函數(shù)檢測
strripos()函數(shù)可以查找字符串在另一字符串中最后一次出現(xiàn)的位置(不區(qū)分大小寫)。
如果指定字符存在,則返回最后一次出現(xiàn)的位置;如果沒有找到,則返回 FALSE。
<?phpheader("content-type:text/html;charset=utf-8"); $findme1 = "C";$findme2 = "c";$mystring = "ABC";$pos1 = strripos($mystring, $findme1);$pos2 = strripos($mystring, $findme2);var_dump($pos1);var_dump($pos2);if($pos1){echo $mystring." 中包含指定字符 $findme1 <br>";}else{echo $mystring." 中不包含指定字符 $findme1 <br>";}if($pos2){echo $mystring." 包含指定字符 $findme2 <br>";}else{echo $mystring." 不包含指定字符 $findme2 <br>";}?>方法5:使用explode()函數(shù)檢測
explode() 函數(shù)使用指定分割符來分割一個字符串,并返回由字符串組成的數(shù)組。
如果數(shù)組不為空數(shù)組(數(shù)組長度大于1),則包含;反之,則數(shù)組為空,進(jìn)而不包含另一個字符串
<?phpheader("content-type:text/html;charset=utf-8"); $url = "001a.gif";$str = "a";$con = explode($str,$url);if (count($con)>1){echo $url." 中包含 ".$str;}else{echo $url." 中沒有包含 ".$str; }?>推薦學(xué)習(xí):《PHP視頻教程》
以上就是php怎么判斷指定字符是否在字符串中的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
關(guān)鍵詞: php字符串