The strrpos() function finds the position of the last occurrence of a string inside another string (case-sensitive).
PHP strrpos() Function has the following syntax.
strrpos(string,find,start)
Parameter | Is Required | Description |
---|---|---|
string | Required. | String to search |
find | Required. | String to find |
start | Optional. | Where to begin the search |
PHP strrpos() Function returns the position of the last occurrence of a string inside another string, or FALSE if the string is not found.
Find the position of the last occurrence of "php" inside the string:
<?php 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.
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 $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 $myString = "Hello, world!"; if ( strrpos( $myString, "Hel" ) === false ){ echo "Not found"; } ?>
The following code shows how to get value from a line using strpos and substr.
<?php $substr = "index.html"; $log = <<< logfile 192.168.1.11:/www/htdocs/index.html:[2010/02/10:20:36:50] 192.168.1.13:/www/htdocs/about.html:[2010/02/11:04:15:23] 192.168.1.15:/www/htdocs/index.html:[2010/02/15:17:25] logfile; // what is first occurrence of the time $substr in log? $pos = strpos($log, $substr); // Find the numerical position of the end of the line $pos2 = strpos($log,"\n",$pos); // Calculate the beginning of the timestamp $pos = $pos + strlen($substr) + 1; // Retrieve the timestamp $timestamp = substr($log,$pos,$pos2-$pos); echo "The file $substr was first accessed on: $timestamp"; ?>
The code above generates the following result.