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

ParameterDescription
haystackRequired. The string where you search
needleRequired. The text that you want to find
offsetOptional. 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

FunctionUse
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
Write a PHP program to reverse the string
Write a PHP program to find the length of the string
Write a PHP program to count the words in the string
Write a PHP program to convert a string into uppercase
Interview Questions & Answers
How will you concatenate two strings in PHP?
What is the difference between single quote and double quote string in PHP?
Why we use PHP String functions trim(), ltrim() and rtrim()?
What PHP Function is used to find position of a string?
What is the use of ucwords() PHP String function?
What is the use of str_replace() PHP String function?
How to find String Length in PHP?