PHP:从路径中获取最后一个目录名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14285134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Get last directory name from path
提问by Code Lover
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 docsfrom above path. Here site_root is nothing but $_SERVER['DOCUMENT_ROOT']So how can I get only docs?
我只想docs从上面的路径中获取。这里 site_root 只不过是$_SERVER['DOCUMENT_ROOT']那么我怎样才能得到docs呢?
Thanks
谢谢
回答by Till Helge
Easiest way would be to use basename($yourpath)as you can see here: http://php.net/basename
最简单的方法是使用,basename($yourpath)如您所见:http: //php.net/basename
回答by mattspain
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 dirnameit first
因此,如果您的字符串包含该文件,请不要忘记先将其命名为
basename(dirname('/home/mypath/test.zip'));
gives
给
mypath
回答by Kapilnemo
This is the easiest way:
这是最简单的方法:
<?php
echo basename(getcwd());
?>
getcwd() = give your full directory path basename() = give you last directory
getcwd() = 给你完整的目录路径 basename() = 给你最后一个目录
回答by C0D3
Try explode('/', '/learnphp/docs/')to split the string into array locations. Then fetch the last location.
尝试explode('/', '/learnphp/docs/')将字符串拆分为数组位置。然后获取最后一个位置。
Here is more info: http://php.net/manual/en/function.explode.php
回答by wezzy
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];
回答by outman
$qa_path=explode('/', '/learnphp/docs/');
echo $qa_path[2]; // output docs
回答by Ankit Agrawal
This will help you
这会帮助你
$qa_path=site_root('/learnphp/docs/');
$q_path = explode ("/", $qa_path);
$lastV = end($q_path);
回答by Pablo S G Pacheco
This gives you the current directory name:
echo basename(dirname(__FILE__));
这为您提供当前目录名称:
echo basename(dirname(__FILE__));

