PHP Manual
Processing of chains

PHP function strpos - occurrence of a substring in a string

26. 11. 2019

Obsah článku

The function finds the position of the first occurrence of the substring in the string, which in human terms means that it checks if the passed string contains the search expression and returns its position.

The strpos function returns the position of the search text in the string. If the string contains it, it returns the position of its first character as integer (integer), if it does not, it returns false (false). This can be used when testing strings.


Parameter Data type Default value Note
$haystack string required String to be searched
$needle mixed required If not a string, it is converted to a number (integer) and used as the ordinal value of the character.
$offset int 0 If a value is set, the function will first subtract the specified number of characters from the beginning of the string before starting the search. Unlike the strrpos and strripos functions, the offset cannot be negative.

String occurrence in text - PHP 8 update

As of PHP 8, there is a native way to verify the existence of a string in text. This is done very simply with the native str_contains function:

if (str_contains('', '@')) {
// The email contains an alias

String occurrence in text

Warning: The str_contains function has been a native part of the language since PHP 8.

We often need to find out if a text contains a certain string. Until PHP 8, the str_contains function did not exist, so it was previously implemented as follows:

* Does $haystack contain the string $needle?
function str_contains(string $haystack, string $needle): bool
return strpos($haystack, $needle) !== false;

For example, you can construct a condition to see if a string contains a second string and then proceed accordingly:

if (strpos('', '@') !== false) {
// The email contains an alias

The advantage of this method of string validation is its extreme speed. If you need to verify a more complex match, regular expressions will be needed.

Return values

The function always returns the string position as an integer (int), or the value false if the string does not contain the search phrase.

Additional resources

[Official strpos function documentation](Official manual)

Jan Barášek   Více o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Související články


V jiných jazycích

All systems normal.