PHP strrpos() Function
In this chapter you will learn:
- Definition for PHP strrpos() Function
- Syntax for PHP strrpos() Function
- Parameter for PHP strrpos() Function
- Return for PHP strrpos() Function
- Related functions for PHP strrpos() Function
- Example - Find the position of the last occurrence of "php" inside the string
- Example - deal with the starting index
Definition
The strrpos() function finds the position of the last occurrence of a string inside another string (case-sensitive).
Syntax
PHP strrpos() Function has the following syntax.
strrpos(string,find,start)
Parameter
Parameter | Is Required | Description |
---|---|---|
string | Required. | String to search |
find | Required. | String to find |
start | Optional. | Where to begin the search |
Return
PHP strrpos() Function returns the position of the last occurrence of a string inside another string, or FALSE if the string is not found.
Related functions
- strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)
- stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)
- strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)
Example 1
Find the position of the last occurrence of "php" inside the string:
<?php//from j av a2 s. c om
echo strrpos("php, from java2s.com!","php");
$myString = "Hello, world!";
echo strpos( $myString, "o" ) . "\n"; // Displays '4'
echo strrpos( $myString, "o" ) . "\n"; // Displays '8'
?>
The code above generates the following result.
Example
When the searched text occurs at the start of the string. In this case, strpos() returns 0 (the index of the first character of the found text), but it's easy to mistake this for a return value of false if you're not careful.
For example, the following code will incorrectly display "Not found" :
<?PHP//from ja va2 s . c om
$myString = "Hello, world!";
if ( !strrpos( $myString, "Hel" ) ) {
echo "Not found";
}
?>
So you need to test explicitly for a false return value, if that's what you're checking for.
The following code works correctly:
<?PHP//from ja v a 2 s . c o m
$myString = "Hello, world!";
if ( strrpos( $myString, "Hel" ) === false ){
echo "Not found";
}
?>
Next chapter...
What you will learn in the next chapter:
- Definition for PHP strspn() Function
- Syntax for PHP strspn() Function
- Parameter for PHP strspn() Function
- Return for PHP strspn() Function
- Example - Return the number of characters found in the string "abcdefand" that contains the characters "abc"