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()
dirname()
only gives you the parent folder's name, sodirname()
will fail wherepathinfo()
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/'
dirname()
and pathinfo()
always return the path without ending slash. And at least in PHP 8.0 dirname()
and pathinfo()
gives you identical results. For 'images/alphabet/abc/'
both functions returns "images/alphabet"
. So currently there's no difference between them.
Apr 21, 2022 at 15:20
<?php
$path = pathinfo('images/alphabet/abc/23345.jpg');
echo $path['dirname'];
?>
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, '/'));
}