strpos() – PHP string first occurance position

PHP strpos function is using for checking the occurrence position of a character or string within a string.It will return the numeric position number of the first occurrence of the searched string.
If strpos function failed to find the searched string , it will return “FLASE”.

For example if we want to know the position of letter “M” in word “MALAYALAM” , strpos function will return the value 0 ( zero ) . It means the searched letter’s position is first on that string.
Please note : Note count is starting from 0 (zero) not from 1 (one )

See the following sample PHP program with strpos function

<?php
$main_string="MALAYALAM";
$search_string="M";
$position  = strpos($main_string, $search_string);
if ($pos==false)
 {
  echo "Searched string was not found in the main string";
 }
else
 {
 echo "found at position ".$position ;
 }
?>

The output of this PHP script will be :
found at position 0

See another example

<?php
$main_string="Hello world";
$search_string="world";
$position  = strpos($main_string, $search_string);
if ($pos==false)
 {
  echo "Searched string was not found in the main string";
 }
else
 {
 echo "found at position ".$position ;
 }
?>

The output of this PHP script will be :
found at position 6

Ok. Now we got the idea about how to get a string’s first occurrence position in another string. But in some situations we need to get the first occurrence position with a offset. It means if need to search the occurrence of a string from a fixed position of the main string than from its starting. ( like we need to start the search from position 3 and avoid first 4 position of the main string ).
You will get a clear picture after seeing the following sample program

<?php
$main_string="MALAYALAM";
$search_string="M";
$position  = strpos($main_string, $search_string, 1);
if ($pos==false)
 {
  echo "Searched string was not found in the main string";
 }
else
 {
 echo "found at position ".$position ;
 }
?>

Output of this program will be
found at position 8

By using the optional offset parameter 1 with strpos function , search will ignore anything before the specified offset value 1 in the main string. So in this example the first M in string MALAYALAM wont consider because it is before the specified offset value 1.

Share
Share
Share