Web Analytics

PHP strpos() Function

String Function PHP 4+

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

ParameterTypeDescription
$haystackstringThe string to search in
$needlestringThe substring to find
$offsetintStart 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 version
  • strrpos() - Find last occurrence
  • substr() - Extract substring
  • str_contains() - PHP 8+ boolean check