PHP strpos() Function

Find the position of the first occurrence of a substring

Try strpos() - edit and run
Output
int(6)
int(0)
bool(false)

What does strpos() do?

strpos() searches $haystack for $needle and returns the 0-based position of the first match, or false if it is not found. The search is case-sensitive.

Syntax

strpos(string $haystack, string $needle, int $offset = 0): int|false

Parameters

  • $haystack - The string to search in.
  • $needle - The substring to look for. Since PHP 8.0 an empty needle is allowed and matches at position 0.
  • $offset - Where to start searching. Negative values start counting from the end.

Return value

The position (int) of the first occurrence, or false if the needle is not found.

strpos() examples

Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.

1. Find a word

<?php
$text = "Hello World";
var_dump(strpos($text, "World"));
var_dump(strpos($text, "Hello"));
var_dump(strpos($text, "world"));

Output:

int(6)
int(0)
bool(false)

2. Always compare with !== false

A match at position 0 is falsy, so a plain if (strpos(...)) treats "found at the start" as "not found".

<?php
$text = "PHP is fun";

if (strpos($text, "PHP")) {
    echo "Found (loose check)\n";
} else {
    echo "Not found (loose check) - wrong!\n";
}

if (strpos($text, "PHP") !== false) {
    echo "Found (strict check)\n";
}

Output:

Not found (loose check) - wrong!
Found (strict check)

3. Find every occurrence and search case-insensitively

<?php
$text = "a-b-c-d";
$positions = [];
$offset = 0;
while (($pos = strpos($text, "-", $offset)) !== false) {
    $positions[] = $pos;
    $offset = $pos + 1;
}
echo implode(", ", $positions) . "\n";

var_dump(stripos("Hello World", "WORLD"));

Output:

1, 3, 5
int(6)

Common mistakes and gotchas

  • Position 0: always use === false / !== false; never rely on truthiness.
  • Just checking presence? On PHP 8+ use str_contains(), which returns a plain boolean.
  • Case sensitivity: use stripos() for a case-insensitive search and strrpos() for the last occurrence.

PHP strpos() FAQ

Why does strpos() return 0 instead of true?

It returns the position of the match. 0 means the needle was found at the very start of the string, which is why you must compare with !== false.

Is strpos() case-sensitive?

Yes. strpos("Hello", "h") returns false. Use stripos() to ignore case.

What should I use instead of strpos() to check if a string contains a word?

On PHP 8.0 or newer, str_contains($haystack, $needle) is clearer. On older versions use strpos($haystack, $needle) !== false.