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?
Old question, but if someone's looking for a way to find occurrences from the END of the string (for example 3rd occurrence of dot from the end) the following function works (didn't want to use oncodes function not to mess with encoding)
$str = "NooooYesYesNo";
function find_occurence_from_end($haystack, $needle, $num) {
for ($i=1; $i <=$num ; $i++) {
# first loop return position of needle
if($i == 1) {
$pos = strrpos($haystack, $needle);
}
# subsequent loops trim haystack to pos and return needle's new position
if($i != 1) {
$haystack = substr($haystack, 0, $pos);
$pos = strrpos($haystack, $needle);
}
}
return $pos;
}
$pos = find_occurence_from_end($str, "Yes", 2);
// 5
It's super simple. Basically each time it finds an occurrence of your needle it "trims" the string to that position. So it keeps on trimming it while returning the latest position each time.