在未知扩展名时检查文件是否存在

在未知扩展名时检查文件是否存在

问题描述:

I know the directory and filename but not the file's extension. What is the best way to determine if /somedir/file.jpg exists if all I have to go on is /somedir/file? My current method would be using a directory iterator to get the filenames of all the files in the directory without the extension and breaking on the first match e.g. if file === file.

我知道目录和文件名,但不知道文件的扩展名。 如果我必须继续 / somedir / file code>,那么确定 /somedir/file.jpg code>是否存在的最佳方法是什么? 我当前的方法是使用目录迭代器来获取目录中所有文件的文件名而没有扩展名,并在第一次匹配时中断,例如 如果 file === file code>。 p> div>

You can use RecursiveCallbackFilterIterator to filter out only matching basename minus the extension:

<?php
$file = './somedir/file';

$filter = new \RecursiveCallbackFilterIterator(
    new \RecursiveDirectoryIterator(dirname($file), \FilesystemIterator::SKIP_DOTS), 
    function ($current, $key, $iterator) use ($file) {
        return !$current->isDir() && $current->getBasename('.'.$current->getExtension()) == basename($file);
    }
);
$iterator = new \RecursiveIteratorIterator($filter);

Then on that you can, check found:

if (iterator_count($iterator) > 0) {
    //found
} else {
    //not found
}

or, get values:

// get the first filepath
$filename = $iterator->getPathname();

// or loop it if your expecting multiple extensions
foreach($iterator as $file) {
   echo $file->getPathname().PHP_EOL;
}

And it that fails, you could always use glob()

if (!empty(glob($file.".*"))) { 
    echo 'File found'; 
}