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

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
How to&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.

Answer:

You can use basename() function:

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

Answer:

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.

Answer:

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

Answer:

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

Answer:

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

Answer:

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

Answer:

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

Answer:

Try this

echo basename(dirname(__FILE__));

or this

echo basename(dirname(__DIR__));

Answer:

You can do

$baseUrl=basename('/path/to/site');
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;`

Answer:

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