一、stripos函數介紹
PHP中有很多函數可以用來查找字符串,其中stripos函數是一個非常常用的函數。stripos函數可以在一個字符串中查找另一個字符串出現的位置,不區分大小寫。它的語法格式如下:
int stripos ( string $haystack , string $needle [, int $offset = 0 ] )
其中,$haystack參數是要查找的字符串,$needle參數是要在$haystack中查找的字符串,$offset可選參數表示從$haystack的哪個位置開始查找,默認為0。
二、查找字符串的位置
stripos函數可以找到匹配的字符串的第一個位置,並以整數形式返回該位置。如果沒有找到,它將返回false。
$value = "Hello World!"; $position = stripos($value, "world"); if ($position === false) { echo "Couldn't find the string"; } else { echo "The string was found at position: " . $position; }
執行上述代碼後,將輸出:“The string was found at position: 6”。這是因為在$haystack字符串中,值“world”第一次出現在位置6處。
三、查找多個匹配字符串的位置
可以使用一個循環來查找$haystack字符串中所有匹配$needle字符串的位置。下面的代碼演示了如何在一個字符串中查找多個匹配字符串的位置。
$value = "Hello World. Hi, John"; $search = array("world", "john"); foreach ($search as $s) { $position = stripos($value, $s); if ($position === false) { echo "Couldn't find the string: " . $s . "
"; } else { echo "The string " . $s . " was found at position: " . $position . "
"; } }
運行上述代碼後,將輸出:“The string world was found at position: 6”,“The string john was found at position: 14”。
四、結合substr函數截取字符串
可以結合substr函數來截取匹配字符串的位置之後的字符串,從而得到匹配字符串之後的內容。
$value = "Hello World. Hi, John"; $search = "wor"; $position = stripos($value, $search); if ($position === false) { echo "Couldn't find the string: " . $search; } else { $result = substr($value, $position + strlen($search)); echo "The remaining string after " . $search . " is: " . $result; }
執行上述代碼後,將輸出:“The remaining string after wor is: ld. Hi, John”。
五、區分大小寫查找字符串位置
相較於stripos函數,strpos函數是區分大小寫的,也可以查找字符串的位置,其語法與stripos函數完全相同,只是在查找時會區分大小寫。下面是一個使用strpos函數的例子:
$value = "Hello World!"; $position = strpos($value, "world"); if ($position === false) { echo "Couldn't find the string"; } else { echo "The string was found at position: " . $position; }
由於strpos函數區分大小寫,上述代碼將輸出:“Couldn’t find the string”。
六、總結
在PHP中,查找字符串的功能非常常用,stripos函數提供了一種非常方便且實用的方法來查找一個字符串是否包含另一個字符串,並返回匹配字符串的位置。無論是查找一個字符串還是查找多個字符串,stripos函數都可以勝任。而區分大小寫的查找可以使用strpos函數來代替。相信在你日常PHP開發中,stripos函數和strpos函數一定會是你的得力工具。
原創文章,作者:OEDW,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/140332.html