问题
I am writing one function for getting some different database query. Now things are going well but only need to get last directory name from defined path.
$qa_path=site_root('/learnphp/docs/');
I wan to get only docs
from above path. Here site_root is nothing but $_SERVER['DOCUMENT_ROOT']
So how can I get only docs
?
Thanks
回答1:
Easiest way would be to use basename($yourpath)
as you can see here: http://php.net/basename
回答2:
Provided answer doesn't work if your string contains the file at the end, like :
basename('/home/mypath/test.zip');
gives
test.zip
So if your string contains the file, don't forget to dirname it first
basename(dirname('/home/mypath/test.zip'));
gives
mypath
回答3:
This is the easiest way:
<?php
echo basename(getcwd());
?>
getcwd() = give your full directory path basename() = give you last directory
回答4:
Try explode('/', '/learnphp/docs/')
to split the string into array locations. Then fetch the last location.
Here is more info: http://php.net/manual/en/function.explode.php
回答5:
you can use this simple snippet:
$qa_path=site_root('/learnphp/docs/');
$qa_path = explode("/", $qa_path);
$qa_path = $qa_path[count($qa_path) - 1];
回答6:
$qa_path=explode('/', '/learnphp/docs/');
echo $qa_path[2]; // output docs
回答7:
This will help you
$qa_path=site_root('/learnphp/docs/');
$q_path = explode ("/", $qa_path);
$lastV = end($q_path);
回答8:
This gives you the current directory name:
echo basename(dirname(__FILE__));
来源:https://stackoverflow.com/questions/14285134/php-get-last-directory-name-from-path