PHP Function Reference

PHP strrchr() Function



The PHP strrchr() function returns a string which starts from last occurrence of the search string to the end of the given string.

Note: The strrchr() function is a binary-safe and a case-sensitive function.

Syntax

strrchr(string, search)

Parameters

string Required. Specify the string to search.
search Required. Specify the string to search for in the given string.
Prior to PHP 8.0.0, if it 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. Depending on the intended behavior, this should either be explicitly cast to string, or an explicit call to chr() should be performed.

Return Value

Returns a string which starts from last occurrence of the search string to the end of the given string. Returns false if search string is not found.

Example: strrchr() example

The example below shows the usage of strrchr() function.

<?php
$str = "To be, or not to be, that is the question";

//displaying a portion of $str starting from 
//last found "be" to the end of it
echo strrchr($str, "be")."\n";
?>

The output of the above code will be:

be, that is the question

Example: using with substr() function

The substr() function can be used with this function to remove the search string from the returned value. Consider the example below:

<?php
//getting the domain name 
$email  = 'john123@example.com';
$domain = substr(strrchr($email, "@"), 1);
echo $domain."\n";

$path = "var/etc/fig/example.jpg";
//getting the last directory 
$dir = substr(strrchr($path, "/"), 1);
echo $dir."\n";

//getting everything after last newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, "\n"), 1);
echo $last."\n";
?>

The output of the above code will be:

example.com
example.jpg
Line 3

❮ PHP String Reference