zl程序教程

您现在的位置是:首页 >  其他

当前栏目

SearchFileContentsPHP搜索目录文本内容的代码

搜索代码 目录 内容 文本
2023-06-13 09:14:16 时间
这个类可以用来搜索在给定的文本目录中的文件。
它可以给定目录遍历递归查找某些文件扩展名的文件。
并打开找到的文件,并检查他们是否包含搜索词语。

它返回一个含有所有文件的列表包含搜索词语数组。

复制代码代码如下:

<?php
/*
Classforsearchingthecontentsofallthefilesinadirectoryanditssubdirectories
Forsupportpleasevisithttp://www.webdigity.com/
*/
classsearchFileContents{
var$dir_name="";//Thedirectorytosearch

var$search_phrase="";//Thephrasetosearchinthefilecontents
var$allowed_file_types=array("php","phps");//Thefiletypesthataresearched
var$foundFiles;//Filesthatcontainthesearchphrasewillbestoredhere
//开源代码OSPHP.COM.Cn
var$myfiles;
functionsearch($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("Emptysearchphrase");

if(empty($this->dir_name))die("Youmustselectadirectorytosearch");
foreach($this->myfilesas$f){
if(in_array(array_pop(explode(".",$f)),$this->allowed_file_types)){//开源OSPhP.COM.CN
$contents=file_get_contents($f);
if(strpos($contents,$this->search_phrase)!==false)
$this->foundFiles[]=$f;
//开源代码OSPhP.COm.CN

}
}
return$this->foundFiles;
}
functionGetDirContents($dir){
if(!is_dir($dir)){die("FunctionGetDirContents:Problemreading:$dir!");}
if($root=@opendir($dir)){
//PHP开源代码

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;//开源OSPhP.COM.CN
}
}
}
return$files;
}
}
//Example:
$search=newsearchFileContents;
$search->search("E:/htdocs/AccessClass","class");//开源代码OSPHP.COM.Cn
var_dump($search->foundFiles);
?>