當前位置: 首頁> 最新文章列表> PHP 字符串查找方法詳解及示例

PHP 字符串查找方法詳解及示例

M66 2025-11-02

PHP 查找字符串的方法

在PHP 中,查找字符串有多種方式,每種方法適合不同的場景。以下將詳細介紹常用方法及示例代碼。

strpos()

作用:在字符串中查找指定子字符串的首次出現位置,如果未找到則返回false。
語法:strpos(string, substring, offset)
參數:

  • string:要搜索的字符串
  • substring:要查找的子字符串
  • offset:可選,指定從字符串的哪個位置開始搜索,默認從0 開始

示例:

 $string = "Hello World";
$substring = "World";
$pos = strpos($string, $substring);
if ($pos !== false) {
    echo "Substring found at position $pos";
} else {
    echo "Substring not found";
}

stripos()

作用:與strpos() 類似,但不區分大小寫。
語法:stripos(string, substring, offset)
參數與strpos() 相同。

strrpos()

作用:查找字符串中指定子字符串的最後一次出現位置,如果未找到則返回false。
語法:strrpos(string, substring, offset)
參數與strpos() 相同。

stristr()

作用:查找字符串中指定子字符串,並返回從子字符串開始到字符串結尾的部分,不區分大小寫。如果未找到則返回false。
語法:stristr(string, substring, ignore_case)
參數:

  • string:要搜索的字符串
  • substring:要查找的子字符串
  • ignore_case:可選,是否忽略大小寫,默認為false

strstr()

作用:與stristr() 類似,但區分大小寫。
語法:strstr(string, substring, ignore_case)
參數與stristr() 相同。

通過以上方法,開發者可以根據實際需求選擇合適的字符串查找函數,靈活處理PHP 字符串搜索問題。