An example for searching text (a word or phrase) in the directory files:

<?php
function search_text_in_directory_files($directory, $text){
    if(file_exists($directory)){
        $files = array();
 
        if($handle=opendir($directory)){
            while(($file=readdir($handle))!==false){
                if($file!="." && $file!=".." && !is_dir($directory."/".$file) && file_exists($directory."/".$file)){
                    $file_content = file_get_contents($directory."/".$file);
 
                    if(preg_match("/".$text."/i",$file_content)){
                        $files[] = $file;
                    }
                }
            }
            closedir($handle);
        }
 
        return $files;
    }
 
    return false;
}
 
$directory = "files";
$text = "text";
 
$found_files = search_text_in_directory_files($directory,$text);
 
if($found_files===false){
    echo("Directory Not Found");
}elseif(empty($found_files)){
    echo("Text Not Found");
}else{
    foreach($found_files as $found_file){
        echo("<p>$found_file</p>");
    }
}
?>
Share

Leave a Reply

Info