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

yipeiwu_com5年前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);
?>

相关文章

深入file_get_contents与curl函数的详解

有些主机服务商把php的allow_url_fopen选项是关闭了,就是没法直接使用file_get_contents来获取远程web页面的内容。那就是可以使用另外一个函数curl。下面...

php+xml编程之xpath的应用实例

本文实例讲述了php+xml编程之xpath的应用。分享给大家供大家参考。具体如下: xpath设计的核心思想:迅速定位到你所需要的元素(或者节点)。PHP 文件在载入xml文件和创建D...

防止本地用户用fsockopen DDOS攻击对策

原因 php脚本部分源码: 复制代码 代码如下: $fp = fsockopen("udp://$ip", $rand, $errno, $errstr, 5); if($fp){ fw...

两种php实现图片上传的方法

两种php实现图片上传的方法

图片上传在项目中经常用到,几乎没有任何一个项目可以脱离图片或者是文件上传。本篇我在这向大家介绍两种常规的上传方式。(注:在这里我们仅仅是对功能的实现,不去做过多的前端的样式) 一、利用f...

PHP EOT定界符的使用详解

结束标识符必须从行的第一列开始。同样,标识符也必须遵循 PHP 中其它任何标签的命名规则:只能包含字母数字下划线,而且必须以下划线或非数字字符开始。 警告 很重要的一点必须指出,结束标识...