PHP strpos

strpos()-To find the position of a string or character within a string

The function, strpos() finds the position of a string within a string. It needs two arguments. First argument is the string in which you want to search and the second argument is the string that you want to search. When the function finds the string then it will return the position of the first match. In case it does not find a match, it will return false.

Let’s understand this with a simple example.

<?php
echo strpos("Learn PHP", "PHP");
?>

The result of the above script will be:

6

The strpos() function can also be used in the following manner:

<?php
$str="Learn PHP";
echo strpos($str, "PHP");
?>

The answer will be the same. Now, let’s see why the result was 6 and not 7. Remeber that the strpos() function always returns a value that is (position – 1). The reason is that the counter starts with 0 and not from 1. When you search for a string, then the position of the first character will be returned.


Finding position of a string using offset

The strpos() function has a third optional argument also. But what is the purpose? When we searched a string using strpos(), it returned the value of the first occurence of the string. But there can be more than one occurence of the string as well and we might be interested in it. For this, we can use the third optional argument in the strpos() function. Let’s see how.

<?php
$str="Learn PHP. Master PHP.";
$pos1=strpos($str, "PHP");
echo "The first occurence of PHP in the string is $pos1.";
$pos2=strpos($str, "PHP", $pos1+1);
echo "<br/>The second occurence of PHP in the string is $pos2.";
?>

The output of this script will be as follows:

The first occurence of PHP in the string is 6.
The second occurence of PHP in the string is 18.

Previous Post

Next Post

Comments are closed.