代码之家  ›  专栏  ›  技术社区  ›  James Skidmore

如何在字符串中查找字符的第二次到最后一次出现?

  •  13
  • James Skidmore  · 技术社区  · 16 年前

    如果可能,只使用标准的PHP函数,如substr()、strrpos()、strpos()等。

    5 回复  |  直到 16 年前
        1
  •  26
  •   brian-brazil    16 年前

    首先,找到最后一个位置:

    $last = strrpos($haystack, $needle);
    if ($last === false) {
      return false;
    }
    

    从那里,找到最后的第二个:

    $next_to_last = strrpos($haystack, $needle, $last - strlen($haystack) - 1);
    
        2
  •  8
  •   Matthew Flaschen    16 年前

    任何向后步骤的一般解决方案:

    function strrpos_count($haystack, $needle, $count)
    {
        if($count <= 0)
            return false;
    
        $len = strlen($haystack);
        $pos = $len;
    
        for($i = 0; $i < $count && $pos; $i++)
            $pos = strrpos($haystack, $needle, $pos - $len - 1);
    
        return $pos;
    }
    
        3
  •  1
  •   Gumbo    16 年前

    strpos :

    $pos = -1; $last = null; $secondLast = null;
    while (($pos = strpos($haystack, $needle, $pos+1)) !== false) {
        $secondLast = $last;
        $last = $pos;
    }
    if (!is_null($secondLast)) {
        echo 'second last occured on '.$secondLast;
    }
    
        4
  •  0
  •   ilya n.    16 年前

    搜索regexp(如果我错了请纠正我,以及如何用php编写):

        r'x[^x]*x[^x]*$'.replace('x',your_char)
    
        5
  •  0
  •   Martin Tilsted    16 年前

    我不认为这可以用strrpos来完成,因为位置开始时不能 按你期望的方式工作。

    Afaik没有任何明显的方法,但是这个函数应该可以做到这一点。(没有真正测试过,但我认为它有效)。

        /** 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;
        }
    

    推荐文章