PHP Find the Xth occurrence of a substring in a string

Posted on September 3, 2017 at 12:37 pm

Function that use strpos() to get the Xth occurrence of a substring in a string:

/**
 * 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 ''; //$number is out of range
    }
}

Credits to Smokey_Bud.

And here is a function that does the same but using preg_match_all():

/**
 * Get position of second 'wide'
 * $pos = strposX('Hello wide wide world', 'wide', 2);
 */
function strposX($haystack, $needle, $number) {
{
    // decode utf8 because of this behaviour: https://bugs.php.net/bug.php?id=37391
    preg_match_all("/$needle/", utf8_decode($haystack), $matches, PREG_OFFSET_CAPTURE);
    return $matches[0][$number-1][1];
}

Credits to oncode.

Other Posts

Updated Posts