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

后端 未结 14 1539
广开言路
广开言路 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条回答
  •  猫巷女王i
    2020-11-27 05:38

    To find second occurrence of the string you can use the strpos along with "offset" parameter, by adding previous offset to strpos.

    $source = "Hello world, how you doing world...world ?";
    $find = "world";
    $offset = 0;
    $findLength = strlen($find);
    $occurrence = 0;
    
    while (($offset = strpos($source, $find, $offset))!== false) {
        if ($occurrence ++) {
          break;
        }
        $offset += $findLength; 
    }
    
    echo $offset;
    

    You can find all the occurrences by storing offset into an array

    while (($offset = strpos($source, $find, $offset))!== false) {
      $occurrences[] = $offset;
      $offset += $findLength; 
    }
    var_export($occurrences);
    

    Or can get a specific occurrence by matching $occurrence

    //find 3rd occurrence
    if ($occurrence ++ == 2) {
        break;
    }
    

提交回复
热议问题