大网数据广告活动
PHP 语言与运行手册

strstr · 查找字符串的首次出现

· 52CE 我爱测

返回 haystack 字符串从 needle 第一次出现的位置开始到 haystack 结尾的字符串。

strstr

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

strstr — 查找字符串的首次出现

说明

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

返回 haystack 字符串从 needle 第一次出现的位置开始到 haystack 结尾的字符串。

注意:

该函数区分大小写。如果想要不区分大小写,请使用 stristr()。

注意:

如果只需要确定特定的 needle 是否存在于 haystack 中,应该使用更快且更少占用内存的 str_contains() 函数。

参数

haystack

输入字符串。

needle

要搜索的字符串。

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

before_needle

若为 true,strstr() 将返回 needle 在 haystack 中的位置之前的部分。

返回值

返回字符串的一部分或者 false(如果未发现 needle)。

更新日志

版本 说明
8.0.0 needle 现在接受空字符串。
8.0.0 不再支持传递 int 作为 needle。
7.3.0 弃用传递 int 作为 needle。

示例

示例 #1 strstr() 示例

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

$user = strstr($email, '@', true);
echo $user, PHP_EOL; // 打印 name
?>

参见

  • preg_match() - 执行匹配正则表达式
  • stristr() - strstr 函数的忽略大小写版本
  • strpos() - 查找字符串首次出现的位置
  • strrchr() - 查找指定字符在字符串中的最后一次出现
  • substr() - 返回字符串的子串

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。