Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

strpos

Finds the position of the first occurrence of a substring.

Syntax

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

Parameters

ParameterTypeDescription
$haystackstringThe string to search in.
$needlestringThe substring to look for.
$offsetintOptional. The position to start searching from.

Return value

int|falseThe position in bytes, or `false` if the substring is absent.

Examples

A match and no match:

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

Output:

int(6)
bool(false)

Position 0 is not false, so compare strictly:

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

Output:

bool(false)
bool(true)

Notes

If you only need to know whether the substring is there, use str_contains() — it leaves no room for a comparison mistake.

See also

  • mb_strpos — Finds the position of the first occurrence of a substring.
  • str_contains — Checks whether a string contains a given substring.
  • substr — Returns part of a string, counting in bytes.

Related recipes

In the tutorial

  • Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.

Thanks for reading!

Donate to the site — we work hard for you.