glob function recursive question

Discussion in 'PHP' started by guest321, Aug 20, 2010.

  1. #1
    I need to create a function that lists subfolders of a given folder, that contain at least one .txt file.
    I found the following function, which displays a list of file that match a pattern in a directory tree:
    function find($dir, $pattern){
    $dir = escapeshellcmd($dir);  
    $files = glob("$dir/$pattern");  
    foreach (glob("$dir/{.[^.]*,*}", GLOB_BRACE|GLOB_ONLYDIR) as $sub_dir) //look in subdirectories
    {
    $arr   = find($sub_dir, $pattern); //recursive call
    $files = array_merge($files, $arr); // merge array with files from subdirectory  
    }  
    return $files;  
    }  
    $txtFiles=find("project/sys","*.txt");
    foreach ($txtFiles as $txtFile)
    {
    echo '<h2>'.$txtFile.'</h2>'; //display all text files
    }
    PHP:
    My question is, how do I change the function to return only folders that contain at least one text file. But, the functions should look inside child folders of "project/sys" and list a child folder only once if that folder or any of its child folders contain at least one text file.

    I'll give an example of the output I'm looking for:
    Folder list
    project/sys/diagram
    project/sys/bin
    project/sys/scripts
    project/sys/styles
    project/sys/meta

    The above folders may not contain a text file directly, but their children folders do. However, I'm not interested in their children folder and I want to list the above level folder only once for each folder.

    Thanks in advance
     
    guest321, Aug 20, 2010 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Check the user comments on this page, there are some examples.

    www.php.net/glob
     
    nico_swd, Aug 20, 2010 IP
  3. guest321

    guest321 Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks, but I didn't find anything useful for this specific need. Any other option?
     
    guest321, Aug 20, 2010 IP