PHP:从路径中删除文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6782895/
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: remove filename from path
提问by George Reith
Say I have an path: images/alphabet/abc/23345.jpg
假设我有一条路径:images/alphabet/abc/23345.jpg
How do I remove the file at the end from the path? So I end up with: images/aphabet/abc/
如何从路径中删除末尾的文件?所以我最终得到:images/aphabet/abc/
回答by abney317
<?php
$path = pathinfo('images/alphabet/abc/23345.jpg');
echo $path['dirname'];
?>
回答by Machado
dirname()
only gives you the parent folder's name, sodirname()
will failwherepathinfo()
will not.
dirname()
只给你父文件夹的名称,因此dirname()
将无法在那里pathinfo()
不会。
For that, you should use pathinfo()
:
为此,您应该使用pathinfo()
:
$dirname = pathinfo('images/alphabet/abc/23345.jpg', PATHINFO_DIRNAME);
The PATHINFO_DIRNAME
tells pathinfo
to directly return the dirname
.
该PATHINFO_DIRNAME
通知pathinfo
直接返回dirname
。
See some examples:
看一些例子:
For path
images/alphabet/abc/23345.jpg
, both works:<?php $dirname = dirname('images/alphabet/abc/23345.jpg'); // $dirname === 'images/alphabet/abc/' $dirname = pathinfo('images/alphabet/abc/23345.jpg', PATHINFO_DIRNAME); // $dirname === 'images/alphabet/abc/'
For path
images/alphabet/abc/
, wheredirname
fails:<?php $dirname = dirname('images/alphabet/abc/'); // $dirname === 'images/alphabet/' $dirname = pathinfo('images/alphabet/abc/', PATHINFO_DIRNAME); // $dirname === 'images/alphabet/abc/'
对于 path
images/alphabet/abc/23345.jpg
,两者都有效:<?php $dirname = dirname('images/alphabet/abc/23345.jpg'); // $dirname === 'images/alphabet/abc/' $dirname = pathinfo('images/alphabet/abc/23345.jpg', PATHINFO_DIRNAME); // $dirname === 'images/alphabet/abc/'
对于 path
images/alphabet/abc/
,dirname
失败的地方:<?php $dirname = dirname('images/alphabet/abc/'); // $dirname === 'images/alphabet/' $dirname = pathinfo('images/alphabet/abc/', PATHINFO_DIRNAME); // $dirname === 'images/alphabet/abc/'