7.7 Searching a Filesystem


You want to make a list of filenames matching a singular pattern in a particular directory.

Technique

Use the glob() function in the File/Find.php file at PEAR:

 <?php include_once 'File/Find.php'; $fsearcher = new File_Find; $matching = $fsearcher->glob ('/\.php$/i',      '/home/designmm/public_html','perl'); ?> 

Or, if you want to search an entire directory tree, use File_Find 's search() method:

 <?php include_once 'File/Find.php'; $fsystem = new File_Find; $matching = $fsearcher->search ('/\.php$/i',      '/home/designmm/public_html','perl'); ?> 

Or, write our own routine and not depend at all on PEAR:

 <?php $dh = dir('/home/designmm/public_html'); while ($entry = $dh->read()) {     if (preg_match('/\.php$/i', $entry)) {         $matching[] = $entry;    } } $dh->close(); ?> 

Comments

The File_Find class from PEAR contains functions to aid you in searching the filesystem; one of those functions is the glob() function. The glob() function will search the current directory (but not subdirectories) for the specified regular expression. The syntax for glob() is as follows :

 array glob( string  regular_expression,  string  directory  [, string  type_of_regex  ]); 

where glob() returns an array of matches via the regular expression in the specified directory. The optional type_of_regex argument enables you to specify (currently) whether you want to use PHP's regular expressions or PCRE library. If the option is left out, PHP's regular expressions are used by default. If you want to specify a case-insensitive search in your PHP regular expression (usually done via eregi () ), you must add '/i' to the end of your PHP regular expression, just as you would do in Perl (see earlier examples).



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net