当前位置: 移动技术网 > IT编程>开发语言>PHP > Search File Contents PHP 搜索目录文本内容的代码

Search File Contents PHP 搜索目录文本内容的代码

2019年05月27日  | 移动技术网IT编程  | 我要评论
这个类可以用来搜索在给定的文本目录中的文件。
它可以给定目录遍历递归查找某些文件扩展名的文件。
并打开找到的文件,并检查他们是否包含搜索词语。

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

复制代码 代码如下:

<?php
/*
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
//开源代码osphp.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) ){ //开源osphp.com.cn
$contents = file_get_contents($f);
if ( strpos($contents, $this->search_phrase) !== false )
$this->foundfiles [] = $f;
//开源代码osphp.com.cn

}
}
return $this->foundfiles;
}
function getdircontents($dir){
if (!is_dir($dir)){die ("function getdircontents: problem reading : $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 = new searchfilecontents;
$search->search('e:/htdocs/accessclass', 'class'); //开源代码osphp.com.cn
var_dump($search->foundfiles);
?>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网