PHP strrpos() Function

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

ParameterIs RequiredDescription
stringRequired.String to search
findRequired.String to find
startOptional.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.

  • 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// w  ww. j a v  a  2  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  w  w w  .  j  av a 2s  . c  o  m
   $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/* w w w. j a va 2 s. c  om*/
   $myString = "Hello, world!"; 
   if ( strrpos( $myString, "Hel" ) === false ){
       echo "Not found";   
   }
?>




















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions