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

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

    function substr_Index( $str, $nth ){
        $str2 = '';
        $posTotal = 0;
        for($i=0; $i < $nth; $i++){
    
            if($str2 != ''){
                $str = $str2;
            }
    
            $pos   = strpos($str, ':');
            $str2  = substr($str, $pos+1);
            $posTotal += $pos+1;
    
        }
        return $posTotal-1;
    }
    
    
    echo substr($mystring, substr_Index( $mystring , 2) );
    

    Function returns position of nth delimiter.

    Second parameter of substr_Index must be bigger than 0;

    To find second occourance use substr_Index( $mystring , 2)

提交回复
热议问题