Php 获取包含字符串的文件的名称
我想获取包含字符串的文件名(在特定文件夹中) 例如:有一个名为“test”的文件夹。在这个文件夹中有三个文件,但其中只有一个包含字符串“hello”。现在我想用PHP返回这个文件的名称 (所有文件都是.txt) 提前谢谢Php 获取包含字符串的文件的名称,php,regex,file,file-get-contents,Php,Regex,File,File Get Contents,我想获取包含字符串的文件名(在特定文件夹中) 例如:有一个名为“test”的文件夹。在这个文件夹中有三个文件,但其中只有一个包含字符串“hello”。现在我想用PHP返回这个文件的名称 (所有文件都是.txt) 提前谢谢 扫描文件夹 打开每个文件/读取内容 使用该函数检查字符串“hello”是否存在 假设*nix环境 下面将生成一个$output变量,其中包含一个具有文件名的数组: $output = exec("grep -l 'hello' test/*.txt"); 获取文件夹中给定扩展
假设*nix环境 下面将生成一个
$output
变量,其中包含一个具有文件名的数组:
$output = exec("grep -l 'hello' test/*.txt");
$data = glob(FOLDER . "*.txt");
// filter
$filter = array();
// read contents of all files
for($i=0; $i<count($data); $i++) {
$file_path = $data[$i];
// open file in read-only mode
$fp = fopen( $file, 'r' );
// read file data
$file_data = fread($fp, filesize($file_path));
// close file handle
fclose($fp);
// make sure we catch CR-only line endings.
$file_data = str_replace("\r", "\n", $file_data);
// match using regexp
if(preg_match('/(hello world)/im', $file_data)) {
$file_name = basename($data[$i]);
array_push($filter, $file_name);
}
}
// output filtered file names
echo nl2br(print_r($filter, TRUE));
$data=glob(文件夹“*.txt”);
//滤器
$filter=array();
//读取所有文件的内容
对于($i=0;$iWell),您必须打开并读取所有文件..哎哟。在PHP中,这将是一件计算成本很高的事情。通过控制台:grep-nr“your string 123456”文件夹,告诉您哪一行位于该文件中,也告诉您该文件夹中的位置,获取文件,在其中执行strpos,成功后返回文件名。现在您正在打开每个文件…这在PHPat中需要很长时间,至少这是一个真正的跨平台solution@RichardBernards打开三个文本文件不会花太长时间,你以为他就是我们正在使用*nix环境..只要exec()可用,这是一个很好的解决方案。@LorenzoMarcon我已经用您有用的注释更新了我的答案这是搜索多字符串:grep-nr“your string 123456”文件夹,位于所有文件和所有子目录中