PHP - Locating Text with strpos() and strrpos()

Introduction

To find out index offset where a string of text occurs within another string, use strpos().

This function takes two parameters as strstr():

  • the string to search, and
  • the search text to look for.

If the text is found, strpos() returns the index of the first character of the text within the string.

If it's not found, strpos() returns false:

Demo

<?php
    $myString = "Hello, world!";
    echo strpos( $myString, "wor" ); // Displays '7'
    echo strpos( $myString, "xyz" ); // Displays '(false)
?>/* w  ww . j  av a 2s  .  c om*/

Result

When the searched text occurs at the start of the string, strpos() returns 0.

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" :

Demo

<?php
    $myString = "Hello, world!";
    if ( !strpos( $myString, "Hel" ) ) echo "Not found";
?>// w w  w.ja  va  2  s .c  o m

Result

To test explicitly for a false return value, if that's what you're checking for.

The following code works correctly:

Demo

<?php
    $myString = "Hello, world!";
    if ( strpos( $myString, "Hel" ) === false ) echo "Not found";
?>//from  www .j a  v a2  s.com

strpos() can take an optional third argument: an index position within the string to start the search.

Here's an example:

Demo

<?php
$myString = "Hello, world!";
echo strpos( $myString, "o" ) . " \n ";    // Displays '4'
echo strpos( $myString, "o", 5 ) . " \n "; // Displays '8'
?>/*from  ww w .  jav a  2s .co m*/

Result

You can use the third argument to find all occurrences of the search text within the string:

Demo

<?php
          $myString = "Hello, world!";
          $pos = 0;//  ww  w.ja  v a 2  s. com
          while ( ( $pos = strpos( $myString, "l", $pos ) ) !== false ) {
             echo "The letter'l'was found at position: $pos \n ";
             $pos++;
          }
?>

Result

strpos() has a sister function, strrpos() , that does basically the same thing; the only difference is that strrpos() finds the last match in the string, rather than the first:

Demo

<?php
$myString = "Hello, world!";
echo strpos( $myString, "o" ) . " \n ";  // Displays'4'
echo strrpos( $myString, "o" ) . " \n "; // Displays'8'
?>/*from  w  w w  .j av a2  s.c  om*/

Result

With strpos() , you can pass an optional third argument indicating the index position from which to start the search.

If this index position is negative, strrpos() starts that many characters from the end of the string.

Related Topic