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


Using the glob() function with an array and wildcard search

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

如何使用glob()函数执行此操作?

您可以简单地提取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();的替代品。

如果您仍然不确定或需要了解更多标志,您可以使用此链接寻求帮助。