The strpos()
function in PHP is used to find the position of the first occurrence of a substring within a string. Its syntax is as follows:
strpos(string $haystack, mixed $needle, int $offset = 0): int|false
$haystack
is the string to search within.$needle
is the substring you want to find.$offset
(optional) specifies the starting position for the search within the haystack.
The function returns the position of the first occurrence of the substring if found, or false
if the substring is not found.
Here’s an example usage of strpos():
$haystack = "Hello, World!";
$needle = "World";
$position = strpos($haystack, $needle);
if ($position !== false) {
echo "Found '$needle' at position $position";
} else {
echo "Substring not found";
}
In this example, strpos()
will find the position of the substring “World” within the string “Hello, World!”. It will output: “Found ‘World’ at position 7″.