note 64114 added to function.scandir
| From: | www dot mdsjack dot bo dot it at osu1 dot php dot net | Date: | Fri, 07 Apr 2006 18:54:34 +0000 |
| Subject: | note 64114 added to function.scandir | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-107535@lists.php.net to get a copy of this message | ||
I would like to share a couple of functions I've made to get an Array of files of a certain
extension inside a Directory.
<?php
// Firstly, a PHP 5 emulation
function php4_scandir($dir, $sort = 0)
{
if (PHP_VERSION >= '5') return scandir($dir, $sort);
$dirmap = array();
if(!is_dir($dir))
{
trigger_error("lib::scandir($dir): failed to open dir: Invalid argument",
E_USER_WARNING);
return false;
}
$dir = opendir($dir);
while (false !== ($file = readdir($dir)))
$dirmap[] = $file;
closedir($dir);
($sort == 1) ? rsort($dirmap) : sort($dirmap);
return $dirmap;
}
/*
Then, this one converts directory files into array items.
It also can filter by file extension.
*/
function dir2arr($dir, $ext = null)
{
$arr = array();
if(PHP_VERSION >= '4.3.0')
{
# PHP 4.3.0 code
if ($dir = glob("$dir*".(!$ext ? '.*' : '{'.$ext.',
'.strtoupper($ext).'}'), GLOB_NOSORT + GLOB_BRACE))
foreach ($dir as $file)
$arr[] = preg_replace("#(?:.+\/{1})*([^\.]+)\.(.+)#i", '$1', $file);
}
else
{
# PHP 4.2.x code
$dir = php4_scandir($dir); // See code snippet above
if(!$ext) $ext = '\.[a-z]+';
$pattern = "#([^\.|\.\.$]+)$ext#i";
foreach ($dir as $file)
if (preg_match($pattern, $file, $filename))
$arr[] = $filename[1];
}
return (empty($arr) ? false : $arr);
}
?>
----
Server IP: 213.92.11.19
Probable Submitter: 151.46.231.222
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.scandir.php
Edit -- http://master.php.net/note/edit/64114
Del: integrated -- http://master.php.net/note/delete/64114/integrated
Del: useless -- http://master.php.net/note/delete/64114/useless
Del: bad code -- http://master.php.net/note/delete/64114/bad+code
Del: spam -- http://master.php.net/note/delete/64114/spam
Del: non-english -- http://master.php.net/note/delete/64114/non-english
Del: in docs -- http://master.php.net/note/delete/64114/in+docs
Del: other reasons-- http://master.php.net/note/delete/64114
Reject -- http://master.php.net/note/reject/64114
Search -- http://master.php.net/manage/user-notes.php