萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 字串查找函數大全:strstr、strpos、substr、strrchr 等用法詳解

PHP 常用字串搜尋與擷取函數完整指南

PHP 提供多種字串查找、截取函數,各有不同回傳值與適用場景。本文整理 strstr、stristr、strpos、stripos、strrpos、strripos、substr、strrchr 等核心函數用法與差異。

1. strstr / stristr — 回傳匹配處至結尾的子字串

string strstr ( string $haystack, mixed $needle [, bool $before_needle = false ] )
string stristr ( string $haystack, mixed $needle [, bool $before_needle = false ] ) // 不區分大小寫
  • $haystack:被搜尋字串;$needle:搜尋目標。
  • 回傳從 $needle 第一次出現處到字串結尾;$before_needle=true 時回傳之前部分 (PHP 5.3+)。
  • 未找到回傳 false。
  • strstr 區分大小寫;stristr 不區分。

範例

<?php
$email = 'user@example.com';
echo strstr($email, '@');       // @example.com
echo strstr($email, '@', true); // user (PHP 5.3+)
echo stristr('Hello WORLD', 'world'); // WORLD
?>

2. strpos / stripos — 回傳首次出現位置 (索引)

int strpos ( string $haystack, mixed $needle [, int $offset = 0 ] )
int stripos ( string $haystack, mixed $needle [, int $offset = 0 ] ) // 不區分大小寫
  • 回傳 $needle 首次出現的整數位置 (0 起算)。
  • $offset 指定起始搜尋位置。
  • 未找到回傳 false;必須用 === false 判斷 (因位置 0 會被視為 false)。
  • 效能最好,僅需判斷是否存在時首選。
  • 多位元組字元 (中文) 支援較差,建議用 mb_strpos/mb_stripos。

範例

<?php
echo strpos('Hello world', 'wo'); // 6
echo stripos('Hello WORLD', 'world'); // 6
?>

3. strrpos / strripos — 回傳最後一次出現位置

int strrpos ( string $haystack, mixed $needle [, int $offset = 0 ] )
int strripos ( string $haystack, mixed $needle [, int $offset = 0 ] ) // 不區分大小寫
  • 搜尋 $needle 最後一次出現位置。
  • $offset 可為負數,表示從結尾倒數位置開始搜尋。

4. substr — 截取子字串 (依位置/長度)

string substr ( string $string, int $start [, int $length ] )
  • $start ≥ 0:從開頭第 $start 個字元開始 (0 為第一個)。
  • $start < 0:從結尾倒數第 |$start| 個字元開始。
  • $length > 0:最多截取 $length 個字元。
  • $length < 0:從結尾省略 |$length| 個字元。
  • $length = 0/null/false:回傳空字串。
  • 省略 $length:截取到字串結尾。

範例

<?php
$str = 'abcdef';
echo substr($str, 2);      // cdef
echo substr($str, -3);     // def
echo substr($str, 0, -1);  // abcde (移除最後一字元)
echo substr($str, 2, -1);  // cde
echo substr($str, -3, -1); // de
?>

5. strrchr — 回傳最後一次出現字元至結尾

string strrchr ( string $haystack, mixed $needle )
  • 回傳 $haystack 中 $needle 最後一次出現位置到結尾的子字串。
  • 常用於取得檔案副檔名:strrchr($filename, '.')。

函數選擇快速決策樹

需求推薦函數備註
判斷子字串是否存在 (高效能)strpos / stripos用 === false 判斷失敗
取得匹配後的內容strstr / stristrstristr 不分大小寫
取得最後匹配位置strrpos / strripos
依位置/長度截取子字串substr支援負數索引
取得最後一次出現字元後內容strrchr如取副檔名
中文/多位元組字串mb_strpos, mb_substr 等需 mbstring 擴展

組合應用範例:取得網域名

<?php
$url = 'https://www.example.com/path/page.html';
$domain = substr(strstr($url, '://'), 3); // 先取 // 後內容,再去掉 //
// 或用 parse_url() 更標準
$parts = parse_url($url);
echo $parts['host']; // www.example.com
?>
copyright © 萬盛學電腦網 all rights reserved