If possible, using only standard PHP functions like substr(), strrpos(), strpos(), etc.
views:
1234answers:
6
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
2009-06-15 23:24:02
+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
2009-06-15 23:30:46
Bah, didn't test this fully. That should do it.
2009-06-16 00:10:50
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
2009-06-15 23:26:16
+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
2009-06-15 23:28:43
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.
2009-06-16 00:01:10
Read the question again; I don't think the OP is permitted to use regexes.
Alan Moore
2009-06-16 01:32:12
A:
Martin Tilsted
2009-06-16 00:01:37
Martin, I agree strrpos is very unintuitive, but I finally got it to work. See my updated answer.
Matthew Flaschen
2009-06-16 00:09:53