PHP String strrchr() Function
The PHP String strrchr() function is used to find for the given character in the given string and returns the portion of the string that begins with the last occurrence of the given character. This function takes three arguments: a string, a search string and a before_search string.
Syntax
Below is the syntax of the PHP String strrchr() function −
string strrchr ( string $string, string $search, bool $before_search = false )
Parameters
Here are the parameters of the strrchr() function −
$string − (Required) It is the string to search in.
$search − (Required) It is the search string. If search has multiple characters, only the first is used.
$before_search − (Optional) It is a boolean value. If true, strrchr() returns the length of the string before the last occurrence of the search.
Return Value
The strrchr() function returns the portion of string which starts at the last occurrence of search and goes until the end of string. And FALSE if needle is not found.
PHP Version
First introduced in core PHP 4, the strrchr() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
Here is the basic example of the PHP String strrchr() function to find for the given character in the given string.
<?php
echo strrchr("Tutorialspoint Website!","Website");
?>
Output
This will generate the below output −
Website!
Example 2
This example shows the usage of the strrchr() function to find the last occurrence of a character in the given string.
<?php // Input string and character to find $string = "Hello World!"; $search = "o"; // Find the last occurrence of the character $result = strrchr($string, $search); // Output the result echo "Result: " . ($result !== false ? $result : "Character not found"); ?>
Output
Here is the outcome of the following code −
Result: orld!
Example 3
This program shows how to handle cases when the character is not present in the given string when you are using strrchr() function.
<?php
$string = "Hello World!";
$search = "x";
// Find the last occurrence of the character
$result = strrchr($string, $search);
// Check and output the result
if ($result === false) {
echo "Character not found.";
} else {
echo "Result: " . $result;
}
?>
Output
This will create the below output −
Character not found.
Example 4
This example uses the before_search parameter with the strrchr() function to get the part of the string before the last occurrence of the character.
<?php $string = "Hello Tutorialspoint!"; $search = "o"; // Get part of the string before the last occurrence of the character $result = strrchr($string, $search); // Output the result echo "Result: " . ($result !== false ? $result : "Character not found"); ?>
Output
Following is the output of the above code −
Result: Hello Tutorialsp