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

Jam*_*ore 14 php string

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

bri*_*zil 27

首先,找到最后的位置:

$last = strrpos($haystack, $needle);
if ($last === false) {
  return false;
}
Run Code Online (Sandbox Code Playgroud)

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

$next_to_last = strrpos($haystack, $needle, $last - strlen($haystack) - 1);
Run Code Online (Sandbox Code Playgroud)


Mat*_*hen 8

任意数量的向后步骤的一般解决方案:

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;
}
Run Code Online (Sandbox Code Playgroud)