The strpos() function is used to find a string or the position of a character within a string.
Once the location is found, the strlen() function will return with the position of the first match. The strlen() function will return FALSE if there is no match found.
The proper syntax to use for the strpos function is:
strpos(what to search, what to search for);
echo strpos("This is my string., my");
In the above example, we are searching for the word “my” in the sentence “This is my string.”.
Using echo, the strpos function will return:
An important note to keep in mind is that when using the strpos function, the number will always begin with 0 and not 1. This is why the result is 8 and not 9.
Also as mentioned above, the strpos function will return with the position of the first match, not every match in the string.
Define An Offset Position With Strpos
We can also define the offset of a search within a given string.
For example, if we used +1 as an offset, we could locate not only the first position of the match, but the second position as well:
$searchstring = "I ate 2 hot dogs, 1 sandwich and 2 hamburgers.";
$first = strpos($searchstring, "5");
echo "The position of 2 in the string was $first
$second = strpos($searchstring, "5", $first + 1);
echo "The position of the second 2 was $second";
The above bit of code would display:
The position of 2 in the string was 6
The position of the second 2 was 33