Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

mb_strpos

Finds the position of the first occurrence of a substring.

Available since: PHP 4

Syntax

mb_strpos(string $haystack, string $needle, int $offset = 0, ?string $encoding = null): int|false

Parameters

ParameterTypeDescription
$haystackstringThe string to search in.
$needlestringThe substring to find.
$offsetintThe position to start searching from.
$encoding?stringThe encoding. Defaults to the internal one, usually UTF-8.

Return value

int|falseThe position of the match, counting from zero, or `false` if the substring is not found.

Examples

Position of a match:

<?php
 
var_dump(mb_strpos('Привет, мир', 'мир'));

Output:

int(8)

When there is no match, false is returned:

<?php
 
var_dump(mb_strpos('Привет, мир', 'PHP'));

Output:

bool(false)

Position 0 also looks like false in a loose comparison, so compare strictly:

<?php
 
$position = mb_strpos('PHP', 'P');
 
var_dump($position === false);
var_dump($position == false);

Output:

bool(false)
bool(true)

Notes

Always compare the result to false with ===. If you only need to know whether the substring is present, str_contains() is simpler.

See also

  • str_contains — Checks whether a string contains a given substring.
  • mb_substr — Returns part of a string.

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.