PHP 8 reference · String Functions
PHP strpos() Function
Find the position of the first occurrence of a substring. Returns false if it's not found, so compare with === false.
PHP 8 Since 4.0
Syntax
strpos(string $haystack, string $needle, int $offset = 0): int|false
Parameters
| Parameter | Description |
|---|---|
haystack |
The string to search in. |
needle |
The string to find. |
offset optional |
Where to start searching; negative counts from the end. Default: 0 |
Return value
The position (from 0), or false.
Examples
<?php
$email = "[email protected]";
$at = strpos($email, "@");
echo $at, "\n";
echo substr($email, $at + 1), "\n";
Output
3 example.com
<?php
$pos = strpos("camel", "c");
if ($pos !== false) {
echo "found at $pos\n"; // 0 is a valid position
}
var_dump(strpos("camel", "z"));
Output
found at 0 bool(false)
Common mistakes
if (strpos($s, "a"))fails when the match is at position 0. Compare with!== false, or usestr_contains()(PHP 8+) when you only need yes or no.
Version history
In other languages
str.find()· Pythonstring.indexOf()· JavaScript
Related
stripos()· Find the position of the first occurrence of a substring, ignoring case. Returns false when there's no match.strrpos()· Find the position of the last occurrence of a substring in a string. Returns false if it isn't found.str_contains()· Check whether a string contains a substring and return true or false. Case-sensitive; added in PHP 8.0.mb_strpos()· Find the character position of the first occurrence of a substring in a multibyte string. Returns false if not found.strstr()· Return the part of a string from the first occurrence of a substring to the end, or the part before it.- PHP Strings · tutorial