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

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

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

5条回答
  •  无人及你
    2021-02-07 11:19

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

提交回复
热议问题