|
|
 |
glob (PHP 4 >= 4.3.0, PHP 5) glob -- Find pathnames matching a pattern Descriptionarray glob ( string pattern [, int flags])
The glob() function searches for all the pathnames
matching pattern according to the rules used by
the libc glob() function, which is similar to the rules used by common
shells. No tilde expansion or parameter substitution is done.
Returns an array containing the matched files/directories or FALSE on
error.
Valid flags:
GLOB_MARK - Adds a slash to each item returned
GLOB_NOSORT - Return files as they appear in the
directory (no sorting)
GLOB_NOCHECK - Return the search pattern if no
files matching it were found
GLOB_NOESCAPE - Backslashes do not quote
metacharacters
GLOB_BRACE - Expands {a,b,c} to match 'a', 'b',
or 'c'
GLOB_ONLYDIR - Return only directory entries
which match the pattern
Megjegyzés:
Before PHP 4.3.3 GLOB_ONLYDIR was
not
available on Windows and other systems not using the GNU
C library.
Példa 1.
Convenient way how glob() can replace
opendir() and friends.
|
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
|
Output will look something like:
funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820 |
|
Megjegyzés:
Ez a függvény nem fog távoli fájlokkal
működni, az a szerver helyi fájlrendszerén lesz keresve.
See also opendir(),
readdir(),
closedir(), and fnmatch().
Paul Gregg / Qube #efnet
31-Mar-2004 03:52
Just threw this together in response to a common question in irc:
Available at: http://www.pgregg.com/projects/
http://www.pgregg.com/projects/php/code/preg_find.phps
preg_find() - A function to search in a directory for files or directories matching a preg_ pattern. Tell it the pattern, the start directory and some optional flags and it will return an array of files and their associated stat() details. If you just want the filenames, just do an array_keys() on the result.
e.g. $files = preg_find("/\.php$/", '.', PREG_FIND_RECURSIVE);
will find all files ending in .php in the current directory and below.
Options are:
// PREG_FIND_RECURSIVE - go into subdirectorys looking for more files
// PREG_FIND_DIRMATCH - return directorys that match the pattern also
// PREG_FIND_FULLPATH - search for the pattern in the full path (dir+file)
// PREG_FIND_NEGATE - return files that don't match the pattern
// to use more than one simple seperate them with a | character
Hope you find it useful.
Paul.
Per Lundberg
25-Nov-2003 04:57
Be aware that on UNIX, * as the pattern will *not* match dot-files and dot-directories. Knowing this will save you some headache. :-) May He bless you.
MichaelSoft
06-Nov-2003 12:28
Note that, in some configurations, the search is case-sensitive! You'll need to have something like:
<?php
$images = glob("/path/to/images/{*.jpg,*.JPG}", GLOB_BRACE);
?>
Also on some servers, I have seen such scripts 'crash' with an CGI Error ("...not returning a complete set of HTTP headers...") when glob could not find any match!
ryan at wonko dot com
30-Oct-2003 08:03
Here's an example of how to use the GLOB_BRACE flag:
<?php
$images = glob("/path/to/images/{*.gif,*.jpg,*.png}", GLOB_BRACE);
?>
It's also worth noting that when using the GLOB_BRACE flag in any version of PHP prior to 4.3.4, PHP will crash if no matches are found.
nutbar at innocent dot com
20-Aug-2003 10:04
Piping the output of "ls" and parsing that if you don't have glob() handy is kind of a bad hack. Here's a far better implementation that uses normal PHP functions that you will find in < 4.3.0.
if ($fp = opendir('.')) {
while (($file = readdir($fp)) !== FALSE) {
if (is_file($file) && preg_match('/\.txt$/', $file)) {
echo "$file\n";
}
}
closedir($fp);
}
It's set to return only files, not directories, but you can change that easily by removing the is_file() check. Also, this gives you the extra power of a full regex pattern matcher which glob() may not be able to provide.
sailux at dreamwiz dot com
27-Jun-2003 07:12
You can count files.
on PHP Version > 4.3.0, not Windows.
function count_files($dir)
{
clearstatcache();
if (!is_dir($dir)) return -1;
if (!preg_match("&/$&", $dir)) $dir .= "/"; // end as '/'
return count(glob($dir."*", GLOB_NOSORT)); - count(glob($dir."*", GLOB_ONLYDIR));
}
Good luck.
sthomas at townnews dot com
12-Mar-2003 12:41
/**
* Recursive version of glob
*
* @return array containing all pattern-matched files.
*
* @param string $sDir Directory to start with.
* @param string $sPattern Pattern to glob for.
* @param int $nFlags Flags sent to glob.
*/
function rglob($sDir, $sPattern, $nFlags = NULL)
{
$sDir = escapeshellcmd($sDir);
// Get the list of all matching files currently in the
// directory.
$aFiles = glob("$sDir/$sPattern", $nFlags);
// Then get a list of all directories in this directory, and
// run ourselves on the resulting array. This is the
// recursion step, which will not execute if there are no
// directories.
foreach (glob("$sDir/*", GLOB_ONLYDIR) as $sSubDir)
{
$aSubFiles = rglob($sSubDir, $sPattern, $nFlags);
$aFiles = array_merge($aFiles, $aSubFiles);
}
// The array we return contains the files we found, and the
// files all of our children found.
return $aFiles;
}
darkmare dot n dot ospam at interaccess dot cl
21-Feb-2003 05:09
working with a web access to a private folder outside the webserver's permision, I needed to list the subdirectories in the following form with a function that recieve "c:\\windows" as the only argument.
\sub1
\sub2
\sub2\another1
\sub2\another2
etc...
About an hour of testing gave me the 'glob_it' function! ;), use it or modify it at will. Hope it helps someone. I use PHP 4 under WIN98SE with APACHE.
*** BEGGINING
function glob_it($directory) { // EXAMPLE: $directory = "C:\\windows"
foreach (glob(str_replace("\\", "/", $directory) . "/*") as $filename) {
if(is_dir($filename)) {
$dirs[] = $filename;
$dirs_aux = glob_it(str_replace("/", "\\", $filename));
for($i=0; $i<sizeof($dirs_aux); $i++) {
$dirs[] = $dirs_aux[$i];
}
}
}
Return @$dirs;
}
*** END
Sorry about the english and the apparently messedup code... it looked good on EditPlus (which RULES by the way :) )
martin dot rode at zeroscale dot com
19-Feb-2003 08:37
If you don't have PHP >= 4.3 available and don't want to hassle with PHP (:-) do something like this on GNU/Linux:
foreach (explode("\n",`find -type d -maxdepth 1 ! -name ".*" -printf "%f\n" `) as $dirname) {
print $dirname;
}
With the "find" you can "glob" whatever you like.
tmm at aon dot at
22-Dec-2002 01:50
I have written my own function for searching files, but it only supports ? and *
However it should be easily expandable.
// e.g. $matches=GetMachingFiles(GetContents("."),"*.txt");
function GetMatchingFiles($files, $search) {
// Split to name and filetype
if(strpos($search,".")) {
$baseexp=substr($search,0,strpos($search,"."));
$typeexp=substr($search,strpos($search,".")+1,strlen($search));
} else {
$baseexp=$search;
$typeexp="";
}
// Escape all regexp Characters
$baseexp=preg_quote($baseexp);
$typeexp=preg_quote($typeexp);
// Allow ? and *
$baseexp=str_replace(array("\*","\?"), array(".*","."), $baseexp);
$typeexp=str_replace(array("\*","\?"), array(".*","."), $typeexp);
// Search for Matches
$i=0;
foreach($files as $file) {
$filename=basename($file);
if(strpos($filename,".")) {
$base=substr($filename,0,strpos($filename,"."));
$type=substr($filename,strpos($filename,".")+1,strlen($filename));
} else {
$base=$filename;
$type="";
}
if(preg_match("/^".$baseexp."$/i",$base) && preg_match("/^".$typeexp."$/i",$type)) {
$matches[$i]=$file;
$i++;
}
}
return $matches;
}
And if someone's searching for a function which gets all files from a directory including the subdirectories:
// Returns all Files contained in given dir, including subdirs
function GetContents($dir,$files=array()) {
if(!($res=opendir($dir))) exit("$dir doesn't exist!");
while(($file=readdir($res))==TRUE)
if($file!="." && $file!="..")
if(is_dir("$dir/$file")) $files=GetContents("$dir/$file",$files);
else array_push($files,"$dir/$file");
closedir($res);
return $files;
}
leon at leonatkinson dot com
18-Oct-2002 03:03
Since this function is a wrapper for the OS function of the same name, you may find it helpful to look at the man page while the exact PHP implementation is sorted out.
You might have some luck passing in the literal values of the constants defined in /usr/include/glob.h. For example, GLOB_NOSORT is defined as (1 << 2), which is 4. In PHP, glob('*.php', 4) will returns an unsorted list for me in RH 7.x. YMMV.
opessin at ifrance dot com
07-Jul-2002 12:48
| |