I understand that this function will get the first occurrence of the string.
But what I want is the 2nd occurrence.
How to go about doing that?
To find second occurrence of the string you can use the strpos along with "offset" parameter, by adding previous offset to strpos.
$source = "Hello world, how you doing world...world ?";
$find = "world";
$offset = 0;
$findLength = strlen($find);
$occurrence = 0;
while (($offset = strpos($source, $find, $offset))!== false) {
if ($occurrence ++) {
break;
}
$offset += $findLength;
}
echo $offset;
You can find all the occurrences by storing offset into an array
while (($offset = strpos($source, $find, $offset))!== false) {
$occurrences[] = $offset;
$offset += $findLength;
}
var_export($occurrences);
Or can get a specific occurrence by matching $occurrence
//find 3rd occurrence
if ($occurrence ++ == 2) {
break;
}