Posted By

Knarf on 06/24/11


Tagged

dir


Versions (?)

Dir


 / Published in: PHP
 

An more advanced dir function. Now we got both dir, dir::regex and dir::wildcard

  1. class dir
  2. {
  3. public static function regex($regex, $path = null, $i = null)
  4. {
  5. if($path == null and $i == null) $first = true;
  6.  
  7. $dirs = explode('/', $regex);
  8.  
  9. if($path == null AND $i == null)
  10. {
  11. for($i=0; $i < count($dirs); $i++)
  12. {
  13. if(!preg_match('/^[a-zA-Z0-9]+$/', $dirs[$i]))
  14. break;
  15. }
  16.  
  17. $path = implode('/', array_slice($dirs, 0, $i));
  18. }
  19.  
  20. $dir = new DirectoryIterator($path);
  21. $ri = new RegexIterator($dir, '/^' . $dirs[$i] . '$/', RegexIterator::ALL_MATCHES);
  22.  
  23. $return_dirs = array();
  24.  
  25. foreach($ri as $item) {
  26. if(isset($item[0][0]) && $item[0][0] != '.' && $item[0][0] != '..')
  27. {
  28. if(is_dir($path . '/' . $item[0][0]) && ($i < (count($dirs) - 1)))
  29. {
  30. $return_dirs[] = self::regex($regex, $path . '/' . $item[0][0], $i + 1);
  31. }
  32. else
  33. {
  34. $return_dirs[] = $path . '/' . $item[0][0];
  35. }
  36. }
  37. }
  38.  
  39. $return_dirs = array_filter($return_dirs, function($array){ return !empty($array); }); // Filter away empty elements
  40.  
  41. if(isset($first) && $first)
  42. {
  43. $return_dirs = call_user_func_array('array_merge', $return_dirs); // Make multidimentional arrays, into single dimention array
  44. }
  45.  
  46. return $return_dirs;
  47. }
  48.  
  49. public static function wildcard($string, $wildcard = '*')
  50. {
  51. $regex = preg_replace('/(\.)/', '\\\\\1', $string); // Escape all . (dot) characters
  52. $regex = preg_replace('/\\' . $wildcard . '/', '.*', $regex); // replace the wildcard
  53. return self::regex($regex);
  54. }
  55. }

Report this snippet  

You need to login to post a comment.