Zend - The PHP Company




Files and Directories

Add Code


search  

Type: code fragment
Added by: h3
Entered: 10/12/2004
Last modified: 01/12/2004
Rating: - (fewer than 3 votes)
Views: 3617
This function was widely inspired by dwebb's File Search function (see: http://www.zend.com/codex.php?id=301&single=1) It's basically the same function but now it returns an array to support multiple matches, it's also more flexible because I used stristr() instead of a literal match, wich is quite useless for a search function...


<?php 
/*----------------------------------------------------------[v2.0]--+
 |    function search($dir,$needle,$recurse=false)                    |
 |                                                                    |
 |    Inputs                                                            |
 |    @param    str        dir        valid path to search in                 |
 |    @param    str        needle    keyword to match                         |
 |    @param    bol        recurse    recursive search (default false)        |
 |                                                                    |
 |    Outputs                                                            |
 |    - false:        no match                                        |
 |    - array:        list of matches                                    |
 |                                                                    |
 |    Author: h3                                                        |
 |    mail:     h3@mindkind.org                                            |
 |    credits: widely inspired from dwebb's File Search function        |
 |            (see: http://www.zend.com/codex.php?id=301&single=1)    |
 |                                                                    |
 +------------------------------------------------------------------*/
function search($dir,$needle,$recurse=false) {
    if(
is_dir($dir)) {
        
$handle = @opendir($dir);
        
$o        = array();
        while(
$file=readdir($handle)) {
            if ((
$file=='.')||($file=='..')) continue;
               if(
stristr(strtolower($file),strtolower($needle))) {
                   
$o[] = $dir.$file;
               }
            if(
is_dir($dir.'/'.$file)&&$recurse==true) {
                
$subresults search($dir.'/'.$file,$needle,true);
                   if(!empty(
$subresults)) {            
                    
$o array_merge($o,$subresults);
                }
               }
        }
        if(!empty(
$o)) {
            return 
$o;
        } else {
            return 
false;
        }
    }
}
?>


Usage Example


<?php
# example
$results search('valid/folder/path/','keyword',true);
echo 
"Results:<ul><li>"implode('</li><li>',$o) ."</li></ul>";
?>


Rate This Script





Search



This Category All Categories