PHP: Find the second (or third) occurrence of a substr in a string
I needed to find the second occurrence of a substring inside of a larger string. PHP has strpos()
which gets you the first occurrence, but nothing beyond that. I wrote a wrapper function around strpos()
to let you specify the number you want to find. Returns false
if nothing is found.
function strpos_num(string $haystack, string $needle, int $num) {
$offset = 0;
$length = strlen($needle);
$pos = null;
for ($i = 0; $i < $num; $i++) {
$pos = strpos($haystack, $needle, $offset);
// Short circuit continued lookups if we don't find anything
if ($pos === false) { return false; }
$offset = $pos + $length;
}
return $pos;
}