PHP strpos() Function
PHP strpos() finds the position of the first occurrence of a text inside another string. It returns the position as a number (starting from 0), or false if the text is not found.
Syntax
strpos(string $haystack, string $needle, int $offset = 0): int|false
Parameters
| Parameter | Description |
|---|---|
| haystack | Required. The string where you search |
| needle | Required. The text that you want to find |
| offset | Optional. The position to start searching from. A negative value counts from the end |
Return value: the position of the first match, or false when not found. The search is case-sensitive.
Examples
Example #1: Find a text
<?php
echo strpos("Hello world!", "world");
?>
Output:
Tutorials Class - Output Window
6
The word “world” starts at position 6, because the first character (H) is at position 0.
Example #2: Search starts from an offset
<?php
echo strpos("Hello world, hello PHP", "o", 5);
?>
Output:
Tutorials Class - Output Window
7
The search starts from position 5, so the “o” in “Hello” (position 4) is skipped, and the next “o” is found in “world”.
Example #3: The 0 and false mistake
If the text is at the very start, strpos() returns 0, and 0 is false-like in a normal comparison. Always compare with !==.
<?php
$text = "Hello world!";
if (strpos($text, "Hello") == false) {
echo "Wrong: says not found<br>";
}
if (strpos($text, "Hello") !== false) {
echo "Correct: found";
}
?>
Output:
Tutorials Class - Output Window
Wrong: says not found
Correct: found
Related functions
| Function | Use |
|---|---|
| stripos() | Same as strpos(), but case-insensitive |
| strrpos() | Finds the last position of the text |
| str_contains() | PHP 8. Only checks if the text exists (true or false) |
| strstr() | Returns the part of the string from the match. See strstr vs stristr |
<?php
echo stripos("Hello World", "world") . "<br>";
echo strrpos("Hello world, hello PHP", "hello");
?>
Output:
Tutorials Class - Output Window
6
13
Note:
If you only need to know if a text exists, use str_contains() in PHP 8. It is simpler and has no 0 problem. See how to check if a string contains a substring.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |