在PHP 中,查找字符串有多種方式,每種方法適合不同的場景。以下將詳細介紹常用方法及示例代碼。
作用:在字符串中查找指定子字符串的首次出現位置,如果未找到則返回false。
語法:strpos(string, substring, offset)
參數:
示例:
$string = "Hello World";
$substring = "World";
$pos = strpos($string, $substring);
if ($pos !== false) {
echo "Substring found at position $pos";
} else {
echo "Substring not found";
}作用:與strpos() 類似,但不區分大小寫。
語法:stripos(string, substring, offset)
參數與strpos() 相同。
作用:查找字符串中指定子字符串的最後一次出現位置,如果未找到則返回false。
語法:strrpos(string, substring, offset)
參數與strpos() 相同。
作用:查找字符串中指定子字符串,並返回從子字符串開始到字符串結尾的部分,不區分大小寫。如果未找到則返回false。
語法:stristr(string, substring, ignore_case)
參數:
作用:與stristr() 類似,但區分大小寫。
語法:strstr(string, substring, ignore_case)
參數與stristr() 相同。
通過以上方法,開發者可以根據實際需求選擇合適的字符串查找函數,靈活處理PHP 字符串搜索問題。