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

yipeiwu_com6年前PHP代码库
这个类可以用来搜索在给定的文本目录中的文件。
它可以给定目录遍历递归查找某些文件扩展名的文件。
并打开找到的文件,并检查他们是否包含搜索词语。

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

复制代码 代码如下:

<?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);
?>

相关文章

PHP基于反射获取一个类中所有的方法

本文实例讲述了PHP基于反射获取一个类中所有的方法。分享给大家供大家参考,具体如下: 当我们使用一个类时既没有源码也没有文档时(尤其是php扩展提供的类,比如mysqli,Redis类)...

PHP 分页类(模仿google)-面试题目解答

笔试回答的不太好,特别是JS部分,也是许久都没复习的原因。 上机题目是要写一个仿google分页的类,当要取类似9/2的最大整数,却怎么也想不起函数ceil的名字,晕了半天。 最后测试程...

php5.3后静态绑定用法详解

php5.3后静态绑定用法详解

本文实例讲述了php5.3后静态绑定用法。分享给大家供大家参考,具体如下: 手册原文: 自 PHP 5.3.0 起,PHP 增加了一个叫做后期静态绑定的功能,用于在继承范围内引用静态调用...

PHP连接SQLServer2005的实现方法(附ntwdblib.dll下载)

PHP连接SQLServer2005的实现方法(附ntwdblib.dll下载)

php连接sql2005的问题,现在整合,同时把FAQ整合上. 我前面写的教程: 连接前配置系统: 1.检查文件 php5.2.5/ntwdblib.dll 默认下面有一个,不能连接再替...

PHP MemCached高级缓存配置图文教程

PHP MemCached高级缓存配置图文教程

1.Memcache相关介绍 memcache是一个高性能的分布式的内存对象缓存系统,它能够用来存储各种格式的数据,包括图像、视频、文件以及数据库检索的结果等。 使用Memcache的网...