Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

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

like image 913
James Skidmore Avatar asked Jun 15 '09 23:06

James Skidmore


People also ask

Where is second occurrence of a character in a string PHP?

Simplest solution for this specific case is to use the offset parameter: $pos = strpos($info, '-', strpos($info, '-') + 1);

How do you get the second last index of a string in Python?

Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.

How do you find the index of the last occurrence of a word in a string?

A simple solution to find the last index of a character in a string is using the rfind() function, which returns the index of the last occurrence in the string where the character is found and returns -1 otherwise.

How do you find the last occurrence position of a character in a text string in Excel?

You can use any character you want. Just make sure it's unique and doesn't appear in the string already. FIND(“@”,SUBSTITUTE(A2,”/”,”@”,LEN(A2)-LEN(SUBSTITUTE(A2,”/”,””))),1) – This part of the formula would give you the position of the last forward slash.


2 Answers

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);
like image 192
brian-brazil Avatar answered Sep 21 '22 13:09

brian-brazil


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;
}
like image 44
Matthew Flaschen Avatar answered Sep 19 '22 13:09

Matthew Flaschen