PHP strrpos() Function
The PHP strrpos() function returns the index number of last occurrence of specified text in the given string. Unlike strripos function, it is a case-sensitive function.
Note: This function is a case-sensitive function.
Syntax
strrpos(string, find, start)
Parameters
string |
Required. Specify the string to search. |
find |
Required. Specify the string to find. 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. |
start |
Optional. Specify the index number from where the search need to start. Default is 0. |
Return Value
Returns the index number of last occurrence of specified text in the given string. Returns false if the find string is not found.
Note: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Therefore, use === operator for testing the return value of this function.
Example:
In the example below, strrpos() function is used to find the index number of last occurrence of "be" in the given string.
<?php $str = "To be, or not to be, that is the question."; echo strrpos($str, "be")."\n"; ?>
The output of the above code will be:
17
Example:
In the example below, last occurrence of "be" is searched after the specified starting position.
<?php $str = "To be, or not to be, that is the question."; echo strrpos($str, "be", 5)."\n"; ?>
The output of the above code will be:
17
Example:
Consider one more example, where === and !== operator is used to test the return value of this function.
<?php $str = "To be, or not to be, that is the question."; $find = "T"; $pos = strrpos($str, $find); //== would not work as expected because the position //of 'T' is 0th (first) character. Use === if ($pos === false) { echo "The string '$find' is not found.\n"; } else { echo "The string '$find' is found at $pos.\n"; } //!= would not work as expected because the position //of 'T' is 0th (first) character. Use !== if ($pos !== false) { echo "The string '$find' is found at $pos.\n"; } else { echo "The string '$find' is not found.\n"; } ?>
The output of the above code will be:
The string 'T' is found at 0. The string 'T' is found at 0.
❮ PHP String Reference