首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP strstr() 函式:取得指定字串後所有內容的實戰技巧

     編輯:PHP 綜合知識

函式定義與參數

string strstr(string $haystack, mixed $needle, bool $before_needle = false)

回傳從 $needle 首次出現位置開始(含本身)到字串結尾的子字串;找不到回傳 false。

基本範例

echo strstr("歡迎來到腳本之家", "腳本"); // 腳本之家
echo strstr("Welcome To www.jb51.net", "jb51"); // jb51.net
echo strstr("123456789", "5"); // 56789

// PHP 5.3+ 取得前段
echo strstr("123456789", "5", true); // 1234

常見應用場景

1. 解析網域/主機名

$url = "https://www.example.com/path?query=1";
$host = strstr($url, '://'); // https://www.example.com/path?query=1
$host = strstr($host, '://', true); // https
// 更穩健請用 parse_url()

2. 截取副檔名

$filename = "document.report.pdf";
$ext = strstr($filename, '.'); // .pdf
// 建議用 pathinfo($filename, PATHINFO_EXTENSION)

3. 簡易模板引擎:提取區塊

$tpl = "[HEADER]...[CONTENT]...[FOOTER]";
$content = strstr($tpl, '[CONTENT]');
$content = strstr($content, '[FOOTER]', true); // [CONTENT]...

效能與替代方案

參數說明
$haystack被搜尋字串
$needle搜尋目標(字串或 ASCII 碼整數)
$before_needletrue 回傳 $needle 前的部分(PHP 5.3+)
函式用途速度備註
strstr單一字串搜尋快C 實作,二進位安全
strpos + substr需精確位置控制略快避免建立中間字串
preg_match複雜模式慢過度殺傷
mb_strstr多位元組編碼中等UTF-8 環境建議使用

最佳實務

  1. 只需判斷是否包含 → 用 strpos($haystack, $needle) !== false,不建立子字串。
  2. 需取得後段內容 → strstr 最簡潔。
  3. 處理 UTF-8 中文 → 改用 mb_strstr,避免截斷多位元組字元。
  4. $needle 為整數時視為 ASCII 碼,較少用,注意別誤傳數值型態。

相關函式速查

  • stristr:不區分大小寫版本。
  • strrchr:尋找字元最後一次出現位置並回傳後段。
  • strchr:strstr 別名。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved