Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to find the position of a substring

Short answer

strpos() returns the position of the first occurrence, counting from zero:

<?php
 
var_dump(strpos('hello world', 'world'));

Output:

int(6)

The zero position trap

If the substring is at the start, the result is 0, and an if (strpos(...)) condition misses it. Compare with false:

<?php
 
$position = strpos('hello world', 'hello');
 
var_dump($position);
var_dump($position !== false);

Output:

int(0)
bool(true)

All occurrences

Search in a loop, each time starting after the previous find:

<?php
 
$text = 'banana';
$positions = [];
$offset = 0;
 
while (($position = strpos($text, 'a', $offset)) !== false) {
    $positions[] = $position;
    $offset = $position + 1;
}
 
echo implode(', ', $positions);

Output:

1, 3, 5

Functions used in this recipe

  • strpos — Finds the position of the first occurrence of a substring.
  • strrpos — Finds the position of the last occurrence of a substring.
  • mb_strpos — Finds the position of the first occurrence of a substring.

Thanks for reading!

Donate to the site — we work hard for you.