duanjing7459 2018-02-03 06:06
浏览 96
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • donglang1894 2018-02-03 06:28
    关注

    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'; 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!