note 92158 added to function.strrpos
| From: | maxmike at gmail dot com | Date: | Sun, 12 Jul 2009 05:05:08 +0000 |
| Subject: | note 92158 added to function.strrpos | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158192@lists.php.net to get a copy of this message | ||
I've got a simple method of performing a reverse strpos which may be of use. This version I
have treats the offset very simply:
Positive offsets search backwards from the supplied string index.
Negative offsets search backwards from the position of the character that many characters from the
end of the string.
Here is an example of backwards stepping through instances of a string with this function:
<?php
function backwardStrpos($haystack, $needle, $offset = 0){
$length = strlen($haystack);
$offset = ($offset > 0)?($length - $offset):abs($offset);
$pos = strpos(strrev($haystack), strrev($needle), $offset);
return ($pos === false)?false:( $length - $pos - strlen($needle) );
}
$pos = 0;
$count = 0;
echo "Test1<br/>";
while(($pos = backwardStrpos("012340567890", "0", $pos)) !== false){
echo $pos."<br/>";
$pos--;
if($pos < 0){
echo "Done<br/>";break;
}
}
echo "---===---<br/>\nTest2<br/>";
echo backwardStrpos("12341234", "1", 2)."<br/>";
echo backwardStrpos("12341234", "1", -2);
?>
Outputs:
Test1
11
5
0
Done
---===---
Test2
0
4
With Test2 the first line checks from the first 3 in "12341234" and runs backwards until
it finds a 1 (at position 0)
The second line checks from the second 2 in "12341234" and seeks towards the beginning for
the first 1 it finds (at position 4).
This function is useful for php4 and also useful if the offset parameter in the existing strrpos is
equally confusing to you as it is for me.
----
Server IP: 66.207.199.35
Probable Submitter: 207.47.201.6
----
Manual Page -- http://www.php.net/manual/en/function.strrpos.php
Edit -- https://master.php.net/note/edit/92158
Del: integrated -- https://master.php.net/note/delete/92158/integrated
Del: useless -- https://master.php.net/note/delete/92158/useless
Del: bad code -- https://master.php.net/note/delete/92158/bad+code
Del: spam -- https://master.php.net/note/delete/92158/spam
Del: non-english -- https://master.php.net/note/delete/92158/non-english
Del: in docs -- https://master.php.net/note/delete/92158/in+docs
Del: other reasons-- https://master.php.net/note/delete/92158
Reject -- https://master.php.net/note/reject/92158
Search -- https://master.php.net/manage/user-notes.php