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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:13:54  来源:igfitidea点击:

PHP: remove filename from path

php

提问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 Byron Whitlock

You want dirname()

你要 dirname()

回答by abney317

<?php
    $path = pathinfo('images/alphabet/abc/23345.jpg');
    echo $path['dirname'];
?>

http://php.net/manual/en/function.pathinfo.php

http://php.net/manual/en/function.pathinfo.php

回答by Machado

dirname()only gives you the parent folder's name, so dirname()will failwhere pathinfo()will not.

dirname()只给你父文件夹的名称,因此dirname()将无法在那里pathinfo()不会

For that, you should use pathinfo():

为此,您应该使用pathinfo()

$dirname = pathinfo('images/alphabet/abc/23345.jpg', PATHINFO_DIRNAME);

The PATHINFO_DIRNAMEtells pathinfoto 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/, where dirnamefails:

    <?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/'