strrchr() returns the portion of a string beginning with the last occurrence of the requested character, or false when it is absent. If the needle contains several characters, only its first character is used. PHP 8.3 and later also support the optional before_needle argument.
$file = 'archive.backup.zip';
echo strrchr($file, '.'); // .zipUse strrchr() for the substring from the last occurrence of a character. For the last position rather than a substring, see strrpos().
strrchr(string $haystack, string $needle): string|false
- $haystack: The input string to search within.$text = "Hello world, welcome to PHP";
$result = strrchr($text, 'o');
echo $result;
Output:
o PHP
Here, the last occurrence of the character "o" is found, and the rest of the string from that point is returned.
.com therefore searches for the final period:
$text = "Welcome to the plus2net.com programming world";
$result = strrchr($text, ".com");
echo $result;
Output:
.com programming world
$text = "Welcome to PHP";
$result = strrchr($text, 'x');
var_dump($result);
Output:
bool(false)
$filename = "document.pdf";
$extension = strrchr($filename, '.');
echo $extension;
Output:
.pdf
This example shows how to get the file extension by searching for the last occurrence of the period . character.
$text = "HELLO World!";
$result = strrchr($text, 'O');
echo $result;
Output:
O World!
Searching for 'O' (uppercase) would not match with lowercase o inside World since it is case-sensitive.
$text = "Hello world, welcome to PHP";
$result = strrchr($text, 'o');
echo $result; // Output: "o PHP"
Using strchr():
$result = strchr($text, 'o');
echo $result; // Output: "o world, welcome to PHP"
pathinfo($filename, PATHINFO_EXTENSION).pathinfo() and URL parsing functions when handling actual paths or URLs.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.