The strpos Function
The strpos
function returns the position
of the first occurrence of a substring in another string
or false
if the substring is not found.
The first parameter is the string
to search in, the second parameter
is the substring to search for.
By default, the function searches from the beginning of the string until the first match. The start of the search can be adjusted with a third optional parameter - if specified, the search will start not from the beginning of the string, but from the specified position.
There is also the stripos
function, which
does the same thing, but case-insensitively.
Syntax
strpos(string $haystack, string $needle, int $offset = 0): int|false
Example
In this example, the function will return the position of the first
character 'c'
. It occupies position 2
,
since the count starts from 0
:
<?php
echo strpos('abcde abcde', 'c');
?>
Code execution result:
2
Example
In this example, the third parameter is specified, so
the search will start from the third position.
In this case, the function will find the second
'c'
character and output its position - 8
:
<?php
echo strpos('abcde abcde', 'c', 3);
?>
Code execution result:
8
Example
If the substring is not found, the function
will return false
. If the string is
at the beginning, the function will return 0
.
This can be a problem when comparing
using the short form of the condition:
<?php
if (strpos('http://site.ru', 'http://')) {
echo '+++';
} else {
echo '---';
}
?>
Code execution result (not what we expected):
'---'
Example
Let's perform the correct check for the beginning of the string:
<?php
if (strpos('http://site.ru', 'http://') === 0) {
echo '+++';
} else {
echo '---';
}
?>
Code execution result:
'+++'
See Also
-
the
strrpos
function,
which returns the position of the last occurrence of a substring -
the
str_contains
function,
which checks for the occurrence of a character in a string -
the
str_starts_with
function,
which checks the beginning of a string -
the
str_ends_with
function,
which checks the end of a string -
the
array_search
function,
which performs an array search