Path get last argument

This function returns the last argument (filename or directory name) of an given path.

function path_get_last_arg($path){
    $path = str_replace('\\', '/', $path); 
    $path = preg_replace('/\/+$/', '', $path);
    $path = explode('/', $path);
    $l = count($path)-1;
    return isset($path[$l]) ? $path[$l] : '';
}
Snippet Details



print path_get_last_arg('c:\\htdocs\\foobar\\file1.php');
// => returns 'file1.php'
 
print path_get_last_arg('/htdocs/usr1/web/');
// => returns 'web'
 
print path_get_last_arg('1/2/3/4');
// => returns '4'

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

Richard Niemand November 17, 2008 at 15:42
function path_get_last_arg($path){
$path = str_replace('\', '/', $path);
$path = preg_replace('//+$/', '', $path);
$path = explode('/', $path);
$l = count($path)-1;
return isset($path[$l]) ? $path[$l] : '';
}

This can be replaced with basename( $path ), or dirname( $path ) :P