How to Find Position of Substring in PHP - strpos() Function

PHP String Functions

The strpos() function finds the numeric position of the first occurrence of a substring (needle) in a string (haystack). The string positions start at 0, and not 1.

Syntax

strpos(string $haystack, string $needle, int $offset = 0)

The function returns the numeric position (index) of the first occurrence of the substring if found, and false if the substring is not present. The position is zero-based, meaning that the first character in the string has a position of 0.

Parameters

  • haystack: The string to search in.
  • needle: The string to search for.
  • offset: If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

Example

$haystack = "Hello, World!";
$needle = "World";
$position = strpos($haystack, $needle);
if ($position !== false)
{
echo "The substring '$needle' was found at position $position.";
}
else
{
echo "The substring '$needle' was not found.";
}

It is important to check for strict inequality (=== or !==) when using strpos() to distinguish between a position of 0 and false.