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

后端 未结 14 1533
广开言路
广开言路 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:22

    Simple is beautiful

    function strposX($haystack, $needle, $n = 0)
    {
        $offset = 0;
    
        for ($i = 0; $i < $n; $i++) {
            $pos = strpos($haystack, $needle, $offset);
    
            if ($pos !== false) {
                $offset = $pos + strlen($needle);
            } else {
                return false;
            }
        }
    
        return $offset;
    }
    
    $offset = strposX($result, "\n", $n);
    
    if ($offset === false) {
        $offset = strlen($result) - 1;
    }
    

提交回复
热议问题