What is the strpos() function in PHP?
Overview
The strpos() method in PHP checks for the position of a string in another string. A string known as the $haystack value will be searched to find another value,
$needle, inside it. For the strpos() method to evaluate as true and return the position of $needle in $haystack, the $needle value has to be a character or a set of characters that must be found in $haystack. Otherwise, it returns false.
Syntax
strpos($haystack,$needle, $offset)
-
$haystack: This is the value that will contain the$needlevalue. -
$needle: This is a set of characters or a single character that may or may not be available in$haystack. -
$offset: This parameter is zero by default. It determines the position in$haystackfrom which the search of$needleshould start. If the offset is negative, the search will start from the end of the$haystack.
Return value
- If the
$needleis found in the$haystack, the return value will be the index position of the$needlein the$haystack. - If the
$needleis not found in the$haystack, the Boolean valuefalsewill be returned.
Code
In the code snippet below, the strpos() method gets the position of the same string in another string:
<?php$searchWord = 'pb';$stringVal1 = 'ijk';$stringVal2 = 'WASPBEE';$valPos1 = stripos($stringVal1, $searchWord);$valPos2 = stripos($stringVal2, $searchWord);// surely, 'pb' is not in 'ijk'if ($valPos1 === false) {echo "The value " . $searchWord . " can't be found in " . $stringVal1 . "\n";}if ($valPos2 !== false) {echo "we saw " . $searchWord ." in ". $stringVal2 . " at index ". $valPos2;}?>
Explanation
-
Line 2, 3, and 4: We declare the
$searchWord,$stringVal1, and$stringVal2variables. -
Line 6 and 7: We use the
strpos()function to find the position of some substrings in them. -
Line 10, 11, and 12: We use the
ifstatement to check what value is returned by thestrpos()function, and iffalseexecutes the code in the block. -
Line 14, 15, and 16: We use the
ifstatement to check what value is returned by thestrpos()function. If it is notfalse, it executes the code in the block.