I do not have PHP 5, so I cannot use strrpos().
Does anyone have a code snippet to find the last occurrence of a string in a string for pre-PHP5?
Printable View
I do not have PHP 5, so I cannot use strrpos().
Does anyone have a code snippet to find the last occurrence of a string in a string for pre-PHP5?
You could use the strrpos() function. ;)
strrpos -- Find position of last occurrence of a char in a string
And,
The needle may be a string of more than one character as of PHP 5.0.0.
So I can't use that.
What I ended up doing though, was:
Although I don't quite like this method.PHP Code:$largestring = //whatever
$reverselarge = strrev($largestring);
$posoflastchevron = strlen($largestring) - strpos($reverselarge, ";781#;pma&");
Hmm... just saw this:
PHP Code:
function strepos($haystack, $needle, $offset=0) {
$pos_rule = ($offset<0)?strlen($haystack)+($offset-1):$offset;
$last_pos = false; $first_run = true;
do {
$pos=strpos($haystack, $needle, (intval($last_pos)+(($first_run)?0:strlen($needle))));
if ($pos!==false && (($offset<0 && $pos <= $pos_rule)||$offset >= 0)) {
$last_pos = $pos;
} else { break; }
$first_run = false;
} while ($pos !== false);
if ($offset>0 && $last_pos<$pos_rule) { $last_pos = false; }
return $last_pos;
}
Sorry :blush: - I didn't read your question.
Although your solution need only be a few lines. This works fine :ehh:
PHP Code:function strrpos_new($haystack, $needle, $offset = 0)
{
/* set initial return value to false, just incase the string
is never found */
$old_pos = false;
/* use strpos() until no match is found */
while (($pos = strpos($haystack, $needle, $offset)) !== false) {
$old_pos = $pos;
$offset = $old_pos + strlen($needle);
}
/* return the old position */
return $old_pos;
}
And this version can handle negative offsets ;)
PHP Code:function strrpos_new($haystack, $needle, $offset = 0)
{
/* check for a negative offset and assertain where
searching should stop */
if ($offset < 0) {
$stop = strlen($haystack) + $offset - 1;
$offset = 0;
} else {
$stop = strlen($haystack) -1;
}
/* set initial return value to false, just incase the string
is never found */
$old_pos = false;
/* use strpos() until no match is found */
while (($pos = strpos($haystack, $needle, $offset)) !== false
&& $pos <= $stop) {
$old_pos = $pos;
$offset = $old_pos + strlen($needle);
}
/* return the old position */
return $old_pos;
}
Be a doll and add [Resolved] to the thread title, will ya? ;)
I shall require a fee for completion of such a service.