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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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
Answers:

Use basename

basename ( 'Home/new_folder/test' );
// 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.

Questions:
Answers:

You can use basename() function:

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

Questions:
Answers:

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.

Questions:
Answers:

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 = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_DIRNAME);
$url_var = explode('/' , $url);
$last_folder = end($url_var);

Questions:
Answers:

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)));

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

Questions:
Answers:

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));
}

Questions:
Answers:
<?php
$path = explode('/', $yourPathVar);
// array_pop gives you the last element of an array()
$last = array_pop($path);
?>

Questions:
Answers:

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

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