'PHP: remove filename from path

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/

php


Solution 1:[1]

You want dirname()

Solution 2:[2]

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

Solution 3:[3]

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

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

Solution 4:[4]

Note that when a string contains only a filename without a path (e.g. "test.txt"), the dirname() and pathinfo() functions return a single dot (".") as a directory, instead of an empty string. And if your string ends with "/", i.e. when a string contains only path without filename, these functions ignore this ending slash and return you a parent directory. In some cases this may be undesirable behavior and you need to use something else. For example, if your path may contain only forward slashes "/", i.e. only one variant (not both slash "/" and backslash "\") then you can use this function:

function stripFileName(string $path): string
{
    if (($pos = strrpos($path, '/')) !== false) {
        return substr($path, 0, $pos);
    } else {
        return '';
    }
}

Or the same thing little shorter, but less clear:

function stripFileName(string $path): string
{
    return substr($path, 0, (int) strrpos($path, '/'));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Byron Whitlock
Solution 2
Solution 3 abney317
Solution 4