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

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

    Old question, but if someone's looking for a way to find occurrences from the END of the string (for example 3rd occurrence of dot from the end) the following function works (didn't want to use oncodes function not to mess with encoding)

    $str = "NooooYesYesNo";
    
    function find_occurence_from_end($haystack, $needle, $num) {
    
        for ($i=1; $i <=$num ; $i++) {
    
            # first loop return position of needle
            if($i == 1) {
                $pos = strrpos($haystack, $needle);
            }
    
            # subsequent loops trim haystack to pos and return needle's new position
            if($i != 1) {
    
                $haystack = substr($haystack, 0, $pos);
                $pos = strrpos($haystack, $needle);
    
            }
    
        }
    
        return $pos;
    
    }
    
    $pos = find_occurence_from_end($str, "Yes", 2);
    
    // 5
    

    It's super simple. Basically each time it finds an occurrence of your needle it "trims" the string to that position. So it keeps on trimming it while returning the latest position each time.

提交回复
热议问题