There is strpos() to find First occurrence, and strrpos() to find last occurrence.
This tutorial explained that it's possible to get any occurrence using a loop, but that might be not fast when the haystack is big. And my code is looking ugly now.
Is there a way to find 2nd, 3rd, 4th, etc occurrence without looping over the haystack? I mean, finding the required occurrence directly without looping? Possible?
You can use a regular expression, but it will not be faster than looping with strpos.
if (preg_match_all("/(match this string)/g",$string,$matches))
{
echo $matches[0] ; // this is the whole string
echo $matches[1] ; // first match
echo $matches[2] ; // second match
echo $matches[3] ; // and so on
}
If you wan to replace those occurrences, use str_replace()
. That way you don't have to worry about offsets.
You can use preg_match()
with the PREG_OFFSET_CAPTURE flag so it'll capture all the matches as well as their position in the source string.
preg_match('/your string/', $source, $matches, PREG_OFFSET_CAPTURE);
$matches will be an array containing the offsets and copies of the matched string