PHP 提供多種字串查找、截取函數,各有不同回傳值與適用場景。本文整理 strstr、stristr、strpos、stripos、strrpos、strripos、substr、strrchr 等核心函數用法與差異。
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
?>
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
?>
int strrpos ( string $haystack, mixed $needle [, int $offset = 0 ] ) int strripos ( string $haystack, mixed $needle [, int $offset = 0 ] ) // 不區分大小寫
$needle 最後一次出現位置。$offset 可為負數,表示從結尾倒數位置開始搜尋。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 ?>
string strrchr ( string $haystack, mixed $needle )
$haystack 中 $needle 最後一次出現位置到結尾的子字串。strrchr($filename, '.')。| 需求 | 推薦函數 | 備註 |
|---|---|---|
| 判斷子字串是否存在 (高效能) | strpos / stripos | 用 === false 判斷失敗 |
| 取得匹配後的內容 | strstr / stristr | stristr 不分大小寫 |
| 取得最後匹配位置 | 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 ?>