Php 如何查找字符串中字符的倒数第二个匹配项?

Php 如何查找字符串中字符的倒数第二个匹配项?,php,string,Php,String,如果可能,只使用标准PHP函数,如substr()、strrpos()、strpos()等。首先,找到最后一个位置: $last = strrpos($haystack, $needle); if ($last === false) { return false; } 从那里,找到最后的第二个: $next_to_last = strrpos($haystack, $needle, $last - strlen($haystack) - 1); 任何数量的后退步骤的一般解决方案: fun

如果可能,只使用标准PHP函数,如substr()、strrpos()、strpos()等。首先,找到最后一个位置:

$last = strrpos($haystack, $needle);
if ($last === false) {
  return false;
}
从那里,找到最后的第二个:

$next_to_last = strrpos($haystack, $needle, $last - strlen($haystack) - 1);

任何数量的后退步骤的一般解决方案:

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;
}
函数strrpos\u count($haystack,$pinder,$count)
{

如果($count与
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;
}
搜索regexp(如果我错了,请纠正我,以及如何用PHP编写):


我不认为用strrpos可以做到这一点,因为位置开始时没有 以你期望的方式工作

虽然没有任何明显的方法,但是这个函数应该可以做到(虽然没有真正测试过,但我认为它可以工作)


Martin,我同意strrpos非常不直观,但我终于让它工作了。请看我的最新答案。呸,没有完全测试这个问题。应该可以。请再读一遍问题;我认为OP不允许使用正则表达式。这正是我想要的,所以tyvm!我不会投票,因为它没有完全回答OP的问题,但我“我很高兴你发布了你的答案。”
    r'x[^x]*x[^x]*$'.replace('x',your_char)
    /** 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;
    }