views:

1234

answers:

6

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

A: 

I would store all occurrence positions in an array by using the method "explode", and then get the second to last array position, and output the position or do what you need with it.

Sev
+5  A: 

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);
Should be noted that this won't work properly in php 4.
Ian Elliott
Bah, didn't test this fully. That should do it.
A: 

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;
}
Matthew Flaschen
+1  A: 

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;
}
Gumbo
A: 

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)
ilya n.
Read the question again; I don't think the OP is permitted to use regexes.
Alan Moore
A: 
Martin Tilsted
Martin, I agree strrpos is very unintuitive, but I finally got it to work. See my updated answer.
Matthew Flaschen