Home » Php » php – How to get the last dir from a path in a string

php – How to get the last dir from a path in a string

Posted by: admin April 23, 2020 Leave a comment


I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

result = test
How to&Answers:

Use basename

// output: test

As a side note to those who answered explode:

To get the trailing name component of a path you should use basename!
In case your path is something like $str = "this/is/something/" the end(explode($str)); combo will fail.


You can use basename() function:

$last = basename("Home/new_folder/test");


You can use pathinfo – pathinfo

$pathinfo = pathinfo('dir/path', PATHINFO_DIRNAME);
$pathinfo = array_filter( explode('/', $pathinfo) );

$result = array_pop($pathinfo);

This will also make sure that a trailing slash doesn’t mean a blank string is returned.


I know it’s an old question, but this automatically gets the last folder without confusing the last item on the list – that could be the script – and not the actual last folder.

$url_var = explode('/' , $url);
$last_folder = end($url_var);


Explode turns the string into an array, you can then choose the last value in that array to be your result.

$result = end((explode('/', $path)));


$directory = 'Home/new_folder/test';
$path = explode('/',$directory);
$lastDir = array_pop($path);


$path = explode('/', $yourPathVar);
// array_pop gives you the last element of an array()
$last = array_pop($path);


So, you want something dynamic that will work most of the time as is– maybe a reusable function or something.

Get the URI from the data the webserver gave you in the request via the $_SERVER data: $_SERVER(‘REQUEST_URI’)

From that URI, get the path: parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH))

basename() is the right tool to get the last directory once you’ve distilled a path from the full URI: basename(parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH))

function lastPathDir() {
    // get a URI, parse the path from it, get the last directory, & spit it out 
    return basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));


Try this

echo basename(dirname(__FILE__));

or this

echo basename(dirname(__DIR__));


You can do

echo $baseUrl;

Incase your URL has '/' at the end you can do:

$url_to_array = parse_url('/path/to/site/');
$baseUrl = basename($url_to_array['path']);
echo $baseUrl;`


This works on windows environtment too, and also works if the path given ends with a slash.

function path_lastdir($p) {
    if (substr($p,-1)=='/') $p=substr($p,0,-1);
    $a=explode('/', $p);
    return array_pop($a);