drci47425
drci47425
采纳率100%
2009-06-15 23:19

如何在字符串中找到倒数第二个字符?

已采纳

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • dtd58256 dtd58256 12年前

    First, find the last position:

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

    From there, find the 2nd last:

    $next_to_last = strrpos($haystack, $needle, $last - strlen($haystack) - 1);
    
    点赞 评论 复制链接分享
  • douyiken0968 douyiken0968 12年前

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

    点赞 评论 复制链接分享
  • dpzjl68484 dpzjl68484 12年前

    Search for a regexp (plz correct me if I'm wrong, and how to write it in PHP):

        r'x[^x]*x[^x]*$'.replace('x',your_char)
    
    点赞 评论 复制链接分享
  • douji1877 douji1877 12年前

    With 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;
    }
    
    点赞 评论 复制链接分享
  • duanshan5259 duanshan5259 12年前

    General solution for any number of backwards steps:

    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;
    }
    
    点赞 评论 复制链接分享