PHP:从路径中删除文件名

时间:2011-07-21 21:14:43

标签: php

说我有路径:images / alphabet / abc / 23345.jpg

如何从路径末尾删除文件?所以我最终得到:images / aphabet / abc /

3 个答案:

答案 0 :(得分:49)

您需要dirname()

答案 1 :(得分:16)

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

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

答案 2 :(得分:11)

  

dirname() 仅为您提供父文件夹的名称,因此dirname() 将失败,其中pathinfo() 将不会< /强>

为此,您应该使用pathinfo()

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

PATHINFO_DIRNAME告诉pathinfo直接返回dirname

查看一些示例:

  • 对于路径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/'
    
  • 对于路径images/alphabet/abc/,其中dirname失败:

    <?php
    
    $dirname = dirname('images/alphabet/abc/'); 
    // $dirname === 'images/alphabet/'
    
    $dirname = pathinfo('images/alphabet/abc/', PATHINFO_DIRNAME); 
    // $dirname === 'images/alphabet/abc/'