Sunday, November 20, 2011

Get the Directories Name by Given Criteria

/*
 * Get the directories name by given criteria.
 *
 * @author    Junaid Atari <mj.atari@gmail.com>
 * @version   1.0
 * @param     string   $dir              Complete path to directory.
 * @param     array    $skipList         Dirs name to be exclude.
 * @param     string   $strictNameRegex  PCRE pattern to filter names
 * @return    array    List of folders name | empty
*/ 
function getDirectryFolders 
   
$dir$skipList = array (), $strictNameRegex '' )
{
    
$listDir = array ();
    
    if ( !
preg_match '@(//|\\\)$@', (string) $dir ) )
        
$dir .= DIRECTORY_SEPARATOR;
    
    
$handler = @opendir $dir );
    
    if ( !
$handler )
        return array ();
    
    
$skipList array_merge ( (array) $skipList, array ( '.''..' ) );
    
    while ( ( 
$sub readdir $handler ) ) !== false )
    { 
        if ( !
in_array $sub$skipList ) && is_dir $dir $sub ) )
        {
            if ( 
trim $strictNameRegex ) )
            {
                if ( (bool) @
preg_match $strictNameRegex$sub ) )
                    
$listDir$sub ] = $dir $sub;
            }
            else
                
$listDir$sub ] = $dir $sub;
        }
    } 
    
    
closedir $handler );
    
    return 
$listDir
}

/*
+---------+
| Example |
+---------+
*/ 
print_r (
    
getDirectryFolders (
        
'c:\htdocs\web',
        array ( 
'includes' ),
        
'/^[a-z0-9_]+$/i'
    
)
);

/*
+--------+
| Output |
+--------+

Array
(
    [backups] => c:\htdocs\web\backups
    [libraries] => c:\htdocs\web\libraries
    [images] => c:\htdocs\web\images
    [logs] => c:\htdocs\web\logs
    [components] => c:\htdocs\web\components
)

*/ 

0 comments:

Post a Comment