简体   繁体   中英

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/

You want dirname()

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

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

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

Note that when a string contains only a filename without a path (eg "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 "/" , ie 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 "/" , ie 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, '/'));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM