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|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $haystack | string | The string to search in. |
| $needle | string | The substring to find. |
| $offset | int | The position to start searching from. |
| $encoding | ?string | The 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.