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

strrchr · 查找指定字符在字符串中的最后一次出现

· 52CE 我爱测

该函数返回 haystack 字符串中的一部分,这部分以 needle 的最后出现位置开始,直到 haystack 末尾。

strrchr

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

strrchr — 查找指定字符在字符串中的最后一次出现

说明

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

该函数返回 haystack 字符串中的一部分,这部分以 needle 的最后出现位置开始,直到 haystack 末尾。

参数

haystack

在该字符串中查找。

needle

如果 needle 包含了多个字符,那么仅使用第一个字符。该行为不同于 strstr()。

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,strrchr() 返回最后一次出现 needle 之前的 haystack 部分(不包括 needle)。

返回值

该函数返回字符串的一部分。如果 needle 未被找到,返回 false。

更新日志

版本 说明
8.3.0 新增 before_needle 参数。
8.0.0 needle 现在接受空字符串。
8.0.0 不再支持将 int 作为 needle 传递。
7.3.0 弃用将 int 作为 needle 传递。

示例

示例 #1 strrchr() 示例

<?php
$ext = strrchr('somefile.txt', '.');
echo "file extension: $ext \n";
$ext = $ext ? strtolower(substr($ext, 1)) : '';
echo "file extension: $ext";
?>

以上示例的输出类似于:

file extension: .txt
file extension: txt

注释

注意:

此函数可安全用于二进制对象。

参见

  • strstr() - 查找字符串的首次出现
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置

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

资料来源与适用范围

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

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

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