Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP strrpos() function

Reference for PHP strrpos(): find the position of the last occurrence of a substring, how negative offsets work, and handy uses like file extensions.

strrpos() returns the zero-based position of the last occurrence of a substring, or false if it never appears. It is the mirror image of strpos(), which reports the first one.

It is handy when the interesting part of a string comes after the final separator: the file name after the last slash, or the extension after the last dot.

PHP
<?php
var_dump(strrpos("a/b/c.txt", "/"));   // int(3)
var_dump(strrpos("abc", "x"));         // bool(false)

Try it

PHP Last slash and last dot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP How offsets restrict the search

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
strrpos(string $haystack, string $needle, int $offset = 0): int|false
Name Description
$haystack The string to search in.
$needle The substring to find.
$offset With a positive value, the search skips that many bytes from the start. With a negative value, the search starts that many bytes from the end and goes backwards, so a match must begin at or before that point.

Return value: the position of the last match as an int, or false.

Errors: a ValueError is thrown if $offset is more than the length of $haystack (or less than its negative).

Usage notes

  • Compare with false, because position 0 is a valid result.
  • The needle is a whole string. Unlike strrchr(), which only uses the first character of its needle, strrpos() matches the entire substring.
  • Negative offsets are subtle. They limit where a match may start, counted from the end; a match can still extend past that point. Experiment (second example) before relying on them.
  • Byte positions. Use mb_strrpos() for character positions in UTF-8 text.
  • Case-insensitive variant: strripos().
  • Extensions and file names. For real paths, basename() and pathinfo() are safer than manual slicing.
  • Return part of the string directly with strrchr() when you want the text from the last occurrence of a single character.