Alexander
Alexander

Reputation: 4219

Removing file path in PHP

In PHP, how would I isolate the filename and extension without anything else?

e.g.

/img/about/picture.jpg
/img/about/picture2.png

becomes

picture.jpg
picture2.png

I think it can be done using a combination of basename and/or realpath, but I'm not terribly sure how to string it together since I'm not exactly an expert in PHP.

Upvotes: 0

Views: 126

Answers (2)

Matthew Poer
Matthew Poer

Reputation: 1682

http://php.net/basename

Basename returns just the file name and extension from an absolute or relative path. Also works for URLs.

Upvotes: 1

dave
dave

Reputation: 64707

I would use pathinfo()

<?php
   $path_parts = pathinfo('/img/about/picture2.png');
   echo $path_parts['dirname'], "\n";
   echo $path_parts['basename'], "\n";
   echo $path_parts['extension'], "\n";
   echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

The above example will output:

/img/about
picture2.png
png
picture2

Upvotes: 2

Related Questions