Home > Article > Backend Development > How Can I Use glob to Search for a Specific File in Subfolders?
Searching a vast array of files scattered across different folders and subfolders can be a daunting task. However, PHP's glob function provides a versatile solution to address this challenge.
Your initial attempt involved using glob to search within the root directory. To extend its reach beyond the root, consider the following two approaches:
1. Recursive glob with rglob function:
The rglob function enhances glob's capabilities by enabling recursive searches. It recursively descends into subdirectories, returning all matching files. For instance:
function rglob($pattern, $flags = 0) { $files = glob($pattern, $flags); foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) { $files = array_merge([], ...[$files, rglob($dir . "/". basename($pattern), $flags)]); } return $files; } $result = rglob($_SERVER['DOCUMENT_ROOT'] . '/test.zip'); var_dump($result);
2. Recursive Directory Iterator:
The RecursiveDirectoryIterator class is another option for recursive file searching. It provides a more flexible and object-oriented approach:
function rsearch($folder, $regPattern) { $dir = new RecursiveDirectoryIterator($folder); $ite = new RecursiveIteratorIterator($dir); $files = new RegexIterator($ite, $regPattern, RegexIterator::GET_MATCH); $fileList = array(); foreach($files as $file) { $fileList = array_merge($fileList, $file); } return $fileList; } $result = rsearch($_SERVER['DOCUMENT_ROOT'], '/.*\/test\.zip/'); var_dump($result);
Both approaches can effectively scan subfolders for the specified file. Choose the one that best suits your project's requirements and preferences.
The above is the detailed content of How Can I Use glob to Search for a Specific File in Subfolders?. For more information, please follow other related articles on the PHP Chinese website!