Question about strpos: how to get 2nd occurrence of a string?

I know this question is kind of old, but here’s a function I wrote to get the Xth occurrence of a substring, which may be helpful for other people that have this issue and stumble over this thread.

/**
 * Find the position of the Xth occurrence of a substring in a string
 * @param $haystack
 * @param $needle
 * @param $number integer > 0
 * @return int
 */
function strposX($haystack, $needle, $number) {
    if ($number == 1) {
        return strpos($haystack, $needle);
    } elseif ($number > 1) {
        return strpos($haystack, $needle, strposX($haystack, $needle, $number - 1) + strlen($needle));
    } else {
        return error_log('Error: Value for parameter $number is out of range');
    }
}

Or a simplified version:

function strposX($haystack, $needle, $number = 0)
{
    return strpos($haystack, $needle,
        $number > 1 ?
        strposX($haystack, $needle, $number - 1) + strlen($needle) : 0
    );
}

Leave a Comment