strstr

(PHP 4, PHP 5, PHP 7, PHP 8)

strstr查找字符串的首次出現(xiàn)

說明

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

返回 haystack 字符串從 needle 第一次出現(xiàn)的位置開始到 haystack 結(jié)尾的字符串。

注意:

該函數(shù)區(qū)分大小寫。如果想要不區(qū)分大小寫,請使用 stristr()

注意:

如果你僅僅想確定 needle 是否存在于 haystack 中,請使用速度更快、耗費(fèi)內(nèi)存更少的 strpos() 函數(shù)。

參數(shù)

haystack

輸入字符串。

needle

如果 needle 不是一個字符串,那么它將被轉(zhuǎn)化為整型并且作為字符的序號來使用。

before_needle

若為 truestrstr() 將返回 needlehaystack 中的位置之前的部分。

返回值

返回字符串的一部分或者 false(如果未發(fā)現(xiàn) needle)。

更新日志

版本 說明
5.3.0 新增可選的 before_needle 參數(shù)。
4.3.0 strstr() 成為二進(jìn)制安全的。

范例

示例 #1 strstr() 范例

<?php
$email  
'name@example.com';
$domain strstr($email'@');
echo 
$domain// 打印 @example.com

$user strstr($email'@'true); // 從 PHP 5.3.0 起
echo $user// 打印 name
?>

參見

  • preg_match() - 執(zhí)行匹配正則表達(dá)式
  • stristr() - strstr 函數(shù)的忽略大小寫版本
  • strpos() - 查找字符串首次出現(xiàn)的位置
  • strrchr() - 查找指定字符在字符串中的最后一次出現(xiàn)
  • substr() - 返回字符串的子串