Reputation: 429
I have a directory - .../dir
- that contains many files - john.txt
, bob.txt
, anne.pdf
, tom.txt
, etc...
I am given a file name, and need to retreive its extension. I have high confidence that for each filename (ie john
, bob
, etc), there is only one file - so there shouldn't be a case when there's both john.txt
and john.pdf
. But let's say in case that this happens, picking only the first file is ok. Let's say PDF since it's earlier alphabetically.
I only found scandir(), but it returns the whole directory. I could search the array it retrns, but I'm hoping, maybe there's something more efficient?
Upvotes: 0
Views: 48
Reputation: 5183
You can try something like this:
$filename = 'ana';
$files = glob($filename . '.*');
if ($files && ($ext = pathinfo($files[0], PATHINFO_EXTENSION))) {
echo $ext;
}
Upvotes: 1
Reputation: 5395
You should check pathinfo()
function for getting an extension.
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
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
?>
As for searching file, in particular, directory you can use a glob()
function
$file = glob("../dir/jon.*");
Upvotes: 1