Search File Contents PHP code to search directory text content_PHP tutorial

WBOY
Release: 2016-07-21 15:41:01
Original
808 people have browsed it

This class can be used to search for files in a given text directory.
It can recursively find files with certain file extensions given a directory traversal.
And open the found files and check if they contain the search terms.

It returns a list of all files containing an array of search terms.

Copy code The code is as follows:

/*
Class for searching the contents of all the files in a directory and its subdirectories
For support please visit http://www.webdigity.com/
*/
class searchFileContents{
var $dir_name = ''; //The directory to search

var $search_phrase = '';//The phrase to search in the file contents
var $allowed_file_types = array('php','phps');//The file types that are searched
var $foundFiles;//Files that contain the search phrase will be stored here
//Open source codeOSPHP.COM.Cn
var $myfiles;
function search($ directory, $search_phrase){
$this->dir_name = $directory;
$this->search_phrase = $search_phrase;

$this->myfiles = $this-> GetDirContents($this->dir_name);
$this->foundFiles = array();
if ( empty($this->search_phrase) ) die('Empty search phrase');

if ( empty($this->dir_name) ) die('You must select a directory to search');
foreach ( $this->myfiles as $f ){
if ( in_array(array_pop(explode ( '.', $f )), $this->allowed_file_types) ){ //Open source OSPhP.COM.CN
$contents = file_get_contents($f);
if ( strpos ($contents, $this->search_phrase) !== false )
$this->foundFiles [] = $f;
//Open source code OSPhP.COm.CN

}
}
return $this->foundFiles;
}
function GetDirContents($dir){
if (!is_dir($dir)){die ("Function GetDirContents: Problem reading : $dir!");}
if ($root=@opendir($dir)){
//PHP open source code

while ($file=readdir($root)){
if($file=="." || $file==".."){continue;}
if(is_dir($dir."/".$file)){

$files=array_merge($files,$this->GetDirContents($dir."/".$file));
}else{
$files[]=$dir."/". $file; //Open source OSPhP.COM.CN
}
}
}
return $files;
}
}
//Example :
$search = new searchFileContents;
$search->search('E:/htdocs/AccessClass', 'class'); //Open source code OSPHP.COM.Cn
var_dump($search->foundFiles);
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321230.htmlTechArticleThis class can be used to search for files in a given text directory. It can recursively find files with certain file extensions given a directory traversal. and open the found files and check that they are...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template