便宜VPS主机精选
提供服务器主机评测信息

深入解析PHP strrpos函数:查找字符串最后一次出现的位置及实用技巧

strrpos 是 PHP 中的一个字符串函数,它用于查找一个字符串在另一个字符串中最后一次出现的位置。这个函数会返回字符串中最后一次出现的起始索引,如果没有找到则返回 false。函数原型如下:

strrpos(string $haystack, string $needle, int $offset = 0): int

参数说明:

  • $haystack:必需,要在其中搜索 $needle 的字符串。
  • $needle:必需,要在 $haystack 中搜索的字符串。
  • $offset:可选,从该索引位置开始向后搜索 $needle。默认值为 0,表示从字符串的开头开始搜索。

示例:

$haystack = 'Hello, welcome to the world of PHP!';
$needle = 'PHP';

// 从字符串开头开始搜索
$position = strrpos($haystack, $needle);
echo "The position of the last occurrence of '{$needle}' is: " . ($position === false ? 'Not found' : "{$position}\n");
// 输出:The position of the last occurrence of 'PHP' is: 28

// 从索引 8 开始搜索
$position = strrpos($haystack, $needle, 8);
echo "The position of the last occurrence of '{$needle}' starting from index 8 is: " . ($position === false ? 'Not found' : "{$position}\n");
// 输出:The position of the last occurrence of 'PHP' starting from index 8 is: 36

在这个示例中,我们首先使用 strrpos 函数查找 $needle$haystack 中最后一次出现的位置,然后从索引 8 开始搜索 $needle

未经允许不得转载:便宜VPS测评 » 深入解析PHP strrpos函数:查找字符串最后一次出现的位置及实用技巧