Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP strpos() function

Reference for PHP strpos(): find the position of the first occurrence of a substring, the 0 versus false pitfall, offsets, negative offsets and ValueError.

strpos() returns the zero-based byte position of the first occurrence of a substring, or false when it is not found. It is the classic way to locate text in a string and the building block for cutting a string at a known marker.

The most common mistake is testing the result for truthiness: a match at the very beginning returns 0, which is falsy. Always compare with false using === or !==. If you only need a yes/no answer, str_contains() is simpler.

PHP
<?php
var_dump(strpos("hello world", "o"));    // int(4)
var_dump(strpos("hello world", "xyz"));  // bool(false)

Try it

PHP Position 0 versus false

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Offsets and finding every match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
strpos(string $haystack, string $needle, int $offset = 0): int|false
Name Description
$haystack The string to search in.
$needle The substring to find. Since PHP 8.0 it may be empty.
$offset Where to start searching. A negative value counts from the end of the string. The returned position is still relative to the start of $haystack.

Return value: the position of the first match as an int, or false if there is none.

Errors: a ValueError is thrown if $offset is greater than the length of $haystack (or smaller than its negative).

Usage notes

  • Use === false / !== false. if (strpos($s, "a")) is wrong when the match is at position 0.
  • Byte positions. With UTF-8 text, the number is a byte offset, not a character count. Use mb_strpos() if you need characters, and feed positions only to functions of the same family (substr() with strpos(), mb_substr() with mb_strpos()).
  • Case-sensitive. stripos() ignores case; strrpos() finds the last match.
  • Empty needle (PHP 8.0+) returns the offset itself (0 by default) instead of a warning.
  • Only need a boolean? Use str_contains(), or str_starts_with() for prefixes.
  • Not a pattern. For patterns use preg_match().
  • Passing a non-string needle is not interpreted as an ASCII code since PHP 8.0; it is converted to a string like any other argument.