PHP Reference ยท String Functions
PHP strrchr() function
Reference for PHP strrchr(): return the part of a string from the last occurrence of a character, the before_needle flag in PHP 8.3 and file extensions.
strrchr() returns the part of a string starting at the last occurrence of a character, including that character. If the character does not occur, it returns false.
Only the first character of the needle is used. This is a common surprise: strrchr($s, "ab") searches for "a", not "ab". For a whole-substring search from the end, use strrpos() with substr().
<?php echo strrchr("/usr/local/bin/php", "/"); // /php echo strrchr("archive.tar.gz", "."); // .gz
Try it
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.
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
strrchr(string $haystack, string $needle, bool $before_needle = false): string|false
| Name | Description |
|---|---|
$haystack |
The string to search in. |
$needle |
Only its first character is used. |
$before_needle |
Added in PHP 8.3. If true, return the part before the last match instead of from it. |
Return value: the portion of $haystack starting at (or, with $before_needle, ending before) the last matching character, or false if not found.
Usage notes
- One character only. Longer needles are silently reduced to their first character.
- Includes the separator. Use
substr($result, 1)to drop it. - Check for
falsebefore using the result. before_needleneeds PHP 8.3. In older versions usesubstr($s, 0, strrpos($s, $char)). The runner here uses PHP 8.5, so the flag works.- Paths and extensions. For file paths prefer
basename(),dirname()andpathinfo(), which handle edge cases such as trailing slashes and dot-files. - Case-sensitive. There is no
strrichr(); lower-case the haystack and needle instead. - Counterpart:
strstr()works from the first occurrence.