dongzhong2008 2014-12-03 00:12
浏览 17
已采纳

PHP - 按模式获取dir中的所有文件名

I found this code to iterate through files in folder:

if (is_dir($dir)) {
  if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {

          ???????????

  }
    closedir($dh);
}

Files have names like: project-1-0, project-1-1, project-5-14, project-6-21 ... Now I need to filter all files and get only these that begins with "project-1-??" How could I do that, should I use blob() function? Is there any simple example? Im using laravel so maybe there is a function in it for that but i couldnt find something useful

  • 写回答

1条回答 默认 最新

  • dopt85756 2014-12-03 02:21
    关注

    glob is very much what you want here. However, being as you appear to be using Laravel (due to the tag), you should look at Laravel's FileSystem class (accessible using the File facade): 4.2 docs. It provides a wrapper for the standard PHP file functions (though doesn't actually add anything to the mix really for your purposes).

    You can do stuff like this:

    if (File::isDirectory($dir)) {
        foreach (File::glob($dir.'/project-1-*') as $projectDir) {
            $actualDir = substr($projectDir, strlen($dir) + 1); // trim the base directory
        }
    }
    

    But if you want a more powerful file-finding system, you can use Symfony's Finder component (docs), which is already included in your project if you're using Laravel (as some Laravel Filesystem methods use it) and you'll be able to do things like this:

    $dirs = Finder::create()->in($dir)->depth(0)->directories()->name('project-1-*');
    // or, if you want to use regex, this should work
    $dirs = Finder::create()->in($dir)->depth(0)->directories()->name('/^project-1-/');
    

    Now, Finder returns an iterator, so you can use PHP's iterator_to_array function to turn it into an array if you need to use it as an array (that said, an iterator is better if you don't need it as an array, for instance foreaching over it).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部