How Can I Use glob to Search for a Specific File in Subfolders?

Barbara Streisand
Release: 2024-11-07 10:18:03
Original
223 people have browsed it

How Can I Use glob to Search for a Specific File in Subfolders?

php glob: Explore Subfolders for a Specific File

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!