Is there a function in PHP to do this? I know of stripos and strrpos, but that's just the first and last.
how to find the nth occurrence of a substring within a string?
I know of stripos and strrpos, but that's just the first and last.
Not quite. They're the first and last starting from a certain position, with the default being the first character.
Try this:
function nth_strpos($str, $substr, $n, $stri = false)
{
if ($stri) {
$str = strtolower($str);
$substr = strtolower($substr);
}
$ct = 0;
$pos = 0;
while (($pos = strpos($str, $substr, $pos)) !== false) {
if (++$ct == $n) {
return $pos;
}
$pos++;
}
return false;
}
Edit: Here's a demo:
$txt = 'Now is the time for all good men to come to the aid of their party.';
$subtxt = 'THE';
if (($nth = nth_strpos($txt, $subtxt, 3, true)) !== false) {
echo substr($txt, $nth);
} else {
echo 'Not found';
}
// Displays:
// their party.