How to find multiple occurance of a string in a target text


May be  all of you know the pros and cons of  strpos() function.

Why we use this function? Actually sometimes we need to track the position of a search string in a long text or a paragraph.

And  so we  use it.

echo strpos($targetstring,$searched_string);

And it it will  always show the first occurance of the searched text but what we will do when we want to get the multiple occurance.

One solution is that we can use the offset as a third parameter for strpos(); And if the offset value is  1 then it will show the second occurance.

And what will  be the solution if we want to show the all occurance of that particular string in a given text or a large string.

The following one with example will be an absolute solution for that:

<?php

$str = “A dhaka is the B dhaka again after C dhaka again dhaka test”;

 

$toFind = “dhaka”;

$total_count =  substr_count($str,$toFind);

$start = 0;

for($i=0;$i<$total_count;$i++)

{

//$pos=0;

echo”<pre>”;

echo $position =  strpos($str,$toFind,$start);

$start = $position+1;

}

?>

In here we want to find the  position of the dhaka for numerous times in accordance with it frequent times position in $str variable.

Look when ever it finds it first position  it hold the value in a variable then due to the loop it search the string again from the immediate next position of the first position  increment it  by 1.

SO when you echo it from that loop it will shows you the each and every position in a chronological order.

Every question regarding this will be accepted with utmost sincerity.

Be happy with the solution and proceed on your desired task.

Thanks.


Leave a Reply