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

后端 未结 14 1551
广开言路
广开言路 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条回答
  •  广开言路
    2020-11-27 05:33

    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
        );
    }
    

提交回复
热议问题