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

后端 未结 14 1535
广开言路
广开言路 2020-11-27 04:38

I understand that this function will get the first occurrence of the string.

But what I want is the 2nd occurrence.

How to go about doing that?

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 05:20

    The recursive function from Smokey_Bud was slowing my script drastically down. Using a regular expression is much faster in this case (for finding any occurence):

    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];
    }
    
    // get position of second 'wide'
    $pos = strposX('Hello wide wide world', 'wide', 2);
    

提交回复
热议问题