strpos
Category: String Functions
PHP 4+
Description
The strpos function finds the position (index) of the first occurrence of a substring within a string. It returns the numeric position if found, or false if not found. Position numbering starts at zero.
Syntax
strpos(string $haystack, mixed $needle [, int $offset = 0])
Parameters
| Parameter | Type | Description |
|---|---|---|
$haystack |
string | The main string to search within |
$needle |
mixed | The value to search for. If a number, treated as ASCII character ordinal |
$offset |
int | Optional — search start position. Default: 0 |
Return Value
Returns the numeric position of the first match, or false if the needle is not found. Always use === (strict comparison) when checking the result, since position 0 is falsy.
Example
<?php $text = "Hello, welcome to PHPvillage!"; // Find position of "welcome" $pos = strpos($text, "welcome"); if ($pos !== false) { echo "Found at position: " . $pos; // 7 } else { echo "Not found."; } ?>
Notes
- This function is case-sensitive. Use
stripos()for case-insensitive search. - Always compare the return value with
!== false, not just!= false. - To find all occurrences, loop and use the
$offsetparameter.