Posted By

Lostindream on 03/13/10


Tagged

php file regexp filter directory regular Expression


Versions (?)

Comfortable directory contents with filters


 / Published in: PHP
 

Very simple to use.

Calling:

$files = dirContents(DIR_PATH, [FILTER, [TYPE]]);

Examples:

$files = dirContens("my-dir");

$files is array containing all, both files either directories

$files = dirContens("my-dir", "img[0-9]");

$files is array containing files or directories with 'img0', 'img1', 'img2', etc. in their names

$files = dirContents("my-dir/", "\.php", 1);

$files is array containing only files with '.php' in their names

Tip: After calling dirContents() try to call print_r for showing the array of files

echo '<pre>';
print_r($files);
echo '</pre>';

Thank you for your comments.

  1. /* Reading directory contents
  2.   * @param STRING $dir - Name of the directory
  3.   * @param STRING $filter - Regular expression
  4.   * @param BOOLEAN $type - 0 => Files and directories, 1 => Only files, 2 => Only directories
  5.   * @return ARRAY|BOOLEAN - Returning array if success, else FALSE */
  6.  
  7. function dirContents($dir, $filter=null, $type=0)
  8. {
  9. $dir .= "/";
  10. $dir = eregi_replace("[\/]+","/", $dir);
  11. if(is_dir($dir) && $d=opendir($dir))
  12. {
  13. $files = array();
  14.  
  15. while(($file=readdir($d)) !== false)
  16. {
  17. if($file!="." && $file!="..")
  18. {
  19. if($type==1 && is_dir($dir.$file)) {continue;}
  20. if($type==2 && !is_dir($dir.$file)) {continue;}
  21. if($filter!==null && !preg_match("/".$filter."/i",$file)) {continue;}
  22. $arrayOfFiles[] = $file;
  23. }
  24. }
  25. closedir($d);
  26. sort($arrayOfFiles,SORT_LOCALE_STRING);
  27. return($arrayOfFiles);
  28.  
  29. }else{return false;}
  30. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Xananax on March 28, 2010

thanks!

Posted By: Xananax on March 28, 2010

you should use "sort()" only if the files match the pattern, or else you get an error: if(count($arrayOfFiles)>0){ sort($arrayOfFiles,SORTLOCALESTRING); }

You need to login to post a comment.