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()
Answer:
<?php
$path = pathinfo('images/alphabet/abc/23345.jpg');
echo $path['dirname'];
?>
Answer:
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/
, wheredirname
fails:<?php $dirname = dirname('images/alphabet/abc/'); // $dirname === 'images/alphabet/' $dirname = pathinfo('images/alphabet/abc/', PATHINFO_DIRNAME); // $dirname === 'images/alphabet/abc/'