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

后端 未结 14 1435
广开言路
广开言路 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:43
    //Finds nth occourance of string after position of given needle.
    //Pass $needle argument as empty string [''] if you want to find from start
    //Pass $needle argument as Int to search string from this position
    
    function substr_Index( $string, $needle, $delimiter, $nth ){
        $str2 = '';
        $posf = strpos($string, $needle);
        if($posf !== false){
            $string   = substr($string, $posf);
            $posTotal = $posf;      
        }else{
            $posTotal = 0;
        }
        
        if( is_int($needle) ){
            $posTotal = $needle;
        }
    
        for($i=0; $i < $nth; $i++){
            
            if($str2 != ''){
                $string = $str2;
            }
                 
            $pos   = strpos($string, $delimiter);
            $str2  = substr($string, $pos + 1);
            $posTotal += $pos+1;
            
        }
        return $posTotal-1;
    }
                   
    //example (returns part of given string from second [:] next from first [#]  )
    $str_ = '..:....:..:....#,61185:9789756130346:0000000:369615:97860510:61436=0000000323636';
    
    echo substr($str_, substr_Index( $str_, '#' , ':', 2) );
    
    0 讨论(0)
  • 2020-11-27 05:44

    You can try this, though I haven't tested it out-

    $pos = strpos($haystack, $needle, strpos($haystack, $needle)+strlen($needle));
    
    0 讨论(0)
提交回复
热议问题