strpos()
strpos() — Find the position of the first occurrence of a substring in a string.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
Signature
strpos(string $haystack, string $needle, int $offset = 0): int|false
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $haystack | string | The string to search in. |
| $needle | string | The string to search for. |
| $offset | int | 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. |
Return value
Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1. Returns false if the needle was not found. This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Example
A runnable snippet:
$mystring = 'abc'; $findme = 'a'; $pos = strpos($mystring, $findme); // Note our use of ===. Simply == would not work as expected // because the position of 'a' was the 0th (first) character. if ($pos === false) { echo "The string '$findme' was not found in the string '$mystring'"; } else { echo "The string '$findme' was found in the string '$mystring'"; echo " and exists at position $pos"; }
Changelog
| Version | Change |
|---|---|
| 8.0.0 | needle now accepts an empty string. |
| 8.0.0 | Passing an int as needle is no longer supported. |
| 7.3.0 | Passing an int as needle has been deprecated. |
| 7.1.0 | Support for negative offsets has been added. |
See also
stripos(), str_contains(), str_ends_with(), str_starts_with(), strrpos(), strripos(), strstr(), strpbrk(), substr(), preg_match()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page strpos() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.