How to find the second-to-last occurrence of a character within a string?

后端 未结 5 1079
别跟我提以往
别跟我提以往 2021-02-07 10:29

If possible, using only standard PHP functions like substr(), strrpos(), strpos(), etc.

5条回答
  •  情歌与酒
    2021-02-07 11:30

    I don't think this can be done with strrpos because the position start does not work in the way you would expect.

    There is afaik not any obvious way, but this function should do it. (Not really tested, but I think it work).

        /** Return the position of the second last needle in haystack or false if nothing is found. I really hate functions with return types that depend on their input, but this function is made to look like the similary php functions (strpos, strrpos and so on) */
    
    // Needle must be a char. If you want it to be a string instead, just substr
    // length of needle instead of 1 in this example.
        function findSecondLastChar($needle,$haystack) {
          $found=0;
          for($pos=strlen($haystack)-1;$pos>=0;$pos--) {
            if(substr($haystack,$pos,1)==$needle) {
              if($found++ == 1)
                return $pos;
            }
          }
           // If we reach this, nothing were found
           return false;
        }
    

提交回复
热议问题