PHP Function Reference

PHP strpos() Function



The PHP strpos() function returns the index number of first occurrence of specified text in the given string. Unlike stripos function, it is a case-sensitive function.

Note: This function is a case-sensitive function.

Syntax

strpos(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 first 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, strpos() function is used to find the index number of first occurrence of "be" in the given string.

<?php
$str = "To be, or not to be, that is the question.";

echo strpos($str, "be")."\n";
?>

The output of the above code will be:

3

Example:

In the example below, first occurrence of "be" is searched after the specified starting position.

<?php
$str = "To be, or not to be, that is the question.";

echo strpos($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 = strpos($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