An example function to show how to iterate through all matches in reverse order: <?phpfunction 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')); echo implode(',', str_positions_reverse('1111111', '11')); $path = '/Users//'.get_current_user().'/./Desktop/path/to/a/file.txt';echo $path; echo 'slashes: ', implode(',', str_positions_reverse( $path, '/'));echo "\nclosest real file: ", str_positions_reverse( $path, '/', function( $pos, $path ){ $path = realpath( substr( $path, 0, $pos )); if( $path !== false ) return $path;});?>