将glob()函数与数组和通配符搜索一起使用

时间:2016-05-07 12:02:35

标签: php

我目前有一个包含文件名的数组,我现在希望foreach通过这个数组使用目录中的通配符搜索并找到匹配的文件。

如何使用glob()功能执行此操作?

1 个答案:

答案 0 :(得分:0)

您只需执行此操作即可在foreach循环中提取与通配符搜索匹配的每个文件:

$search = "*.txt";
// if this is what you mean by indexed string variable?
$file = array("updated.txt", "new.txt"); 

// getcwd() will retrieve the current directory but is not needed - this just shows
// that you can supply a directory if you wanted to.

function MatchFile($file,$search)
{
    $temp = array();
    $i = 0;
    foreach (glob(getcwd().$search) as $filename) :
        if (count($file) > $i):
            array_push($temp, ($filename == $file[$i++])? $filename : "");
        else:
            // stops the index overflow error
            break;
        endif;
    endforeach;
    return $temp;
}

foreach (MatchFile($file,$search) as $found):
    echo $found . " was found!";
endforeach;

这只是opendir();的替代。

如果您仍然不确定或需要了解更多标记,可以使用此link获取帮助。