Home » Php » PHP: remove filename from path

PHP: remove filename from path

Posted by: admin April 23, 2020 Leave a comment

Questions:

Say I have an path: 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/

How to&Answers:

You want dirname()

Answer:

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

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

Answer:

dirname() only gives you the parent folder’s name, so dirname() will fail where pathinfo() will not.

For that, you should use pathinfo():

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

The PATHINFO_DIRNAME tells pathinfo to directly return the 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 dirname fails:

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