| Newsgroups |
php.notes |
| Message-ID |
<[email protected]> |
An example function to show how to iterate through all matches in reverse order:
<?php
function str_positions_reverse( $haystack, $needle, $fn = null ){
if( $fn === null ) $positions = array();
$needlen = strlen( $needle );
$offset = strlen( $haystack ) + $needlen;
$pos = strrpos( $haystack, $needle );
while( $pos !== false ){
if( $fn === null ) $positions[] = $pos;
else if( null !== ( $r = $fn( $pos, $haystack, $needle ))) return $r;
if( $pos < $needlen ) break;
$pos = strrpos( $haystack, $needle, $pos - $offset );
}
if( $fn === null ) return $positions;
}
echo implode(',', str_positions_reverse('111111', '11')); // 4,2,0
echo implode(',', str_positions_reverse('1111111', '11')); // 5,3,1
$path = '/Users//'.get_current_user().'/./Desktop/path/to/a/file.txt';
echo $path; // /Users//alfred.e.neumann/./Desktop/path/to/a/file.txt
echo 'slashes: ', implode(',', str_positions_reverse( $path, '/'));
// slashes: 44,42,39,34,26,24,7,6,0
echo "\nclosest real file: ", str_positions_reverse( $path, '/', function( $pos, $path ){
$path = realpath( substr( $path, 0, $pos ));
if( $path !== false ) return $path;
});
// closest real file: /Users/alfred.e.neumann/Desktop
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 188.143.70.42)
----
Manual Page -- https://php.net/manual/en/function.strrpos.php
Edit -- https://main.php.net/note/edit/130538
Del: integrated -- https://main.php.net/note/delete/130538/integrated
Del: useless -- https://main.php.net/note/delete/130538/useless
Del: bad code -- https://main.php.net/note/delete/130538/bad+code
Del: spam -- https://main.php.net/note/delete/130538/spam
Del: non-english -- https://main.php.net/note/delete/130538/non-english
Del: in docs -- https://main.php.net/note/delete/130538/in+docs
Del: other reasons-- https://main.php.net/note/delete/130538
Reject -- https://main.php.net/note/reject/130538
Search -- https://main.php.net/manage/user-notes.php