note 60562 added to class.dir
| From: | fordiman at gmail dot com | Date: | Wed, 11 Jan 2006 06:05:59 +0000 |
| Subject: | note 60562 added to class.dir | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-101530@lists.php.net to get a copy of this message | ||
This one's pretty nice. After getting frustrated for hunting down .jpg files in my massive
music collection (PHP would run out of memory), I thought there should be a preg_ls function.
function preg_ls ($path=".", $rec=false, $pat="/.*/") {
// it's going to be used repeatedly, ensure we compile it for speed.
$pat=preg_replace("|(/.*/[^S]*)|s", "\\1S", $pat);
//Remove trailing slashes from path
while (substr($path,-1,1)=="/") $path=substr($path,0,-1);
//also, make sure that $path is a directory and repair any screwups
if (!is_dir($path)) $path=dirname($path);
//assert either truth or falsehoold of $rec, allow no scalars to mean truth
if ($rec!==true) $rec=false;
//get a directory handle
$d=dir($path);
//initialise the output array
$ret=Array();
//loop, reading until there's no more to read
while (false!==($e=$d->read())) {
//Ignore parent- and self-links
if (($e==".")||($e=="..")) continue;
//If we're working recursively and it's a directory, grab and merge
if ($rec && is_dir($path."/".$e)) {
$ret=array_merge($ret,preg_ls($path."/".$e,$rec,$pat));
continue;
}
//If it don't match, exclude it
if (!preg_match($pat,$e)) continue;
//In all other cases, add it to the output array
$ret[]=$path."/".$e;
}
//finally, return the array
return $ret;
}
Not bad for a mere 18 lines, don't you think?
Example use:
foreach (preg_ls("/etc/X11", true, "/.*\.conf/i") as $file) echo
$file."\n";
Output:
/etc/X11/xkb/README.config
/etc/X11/xorg.conf-vesa
/etc/X11/xorg.conf~
/etc/X11/gui.conf
/etc/X11/xorg.conf
/etc/X11/xorg.conf-fbdev
----
Manual Page -- http://www.php.net/manual/en/class.dir.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+60562
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60562&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60562&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60562&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60562&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60562&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60562&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60562&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+60562&report=yes
Search -- http://master.php.net/manage/user-notes.php