PHP strpos() Function
The strpos() function finds the position of the first occurrence of a substring in a string.
Syntax
strpos(string $haystack, string $needle, int $offset = 0): int|false
Parameters
| Parameter | Type | Description |
|---|---|---|
$haystack | string | The string to search in |
$needle | string | The substring to find |
$offset | int | Start search from this position (optional) |
Return Value
Returns the position (0-indexed) of the first occurrence, or false if not found.
Try It Online
Output
Click Run to execute your code
More Examples
Check if String Contains
<?php
$str = "Hello World";
if (strpos($str, "World") !== false) {
echo "Found!";
}
?>
Case-Insensitive Search
<?php
$str = "Hello World";
echo stripos($str, "world"); // 6 (case-insensitive)
?>
Important: Always use
=== false or !== false when checking the result, because position 0 is valid but falsy.
Common Use Cases
- Checking if string contains a substring
- Finding email domain (@gmail.com)
- Parsing URLs and paths
- Validating input formats
Related Functions
stripos()- Case-insensitive versionstrrpos()- Find last occurrence- substr() - Extract substring
str_contains()- PHP 8+ boolean check
Enjoying these tutorials?