Php 如何在目录中的所有txt文件中搜索单词
我有一个目录Php 如何在目录中的所有txt文件中搜索单词,php,search,fopen,Php,Search,Fopen,我有一个目录messages,里面有很多txt文件 要在.txt文件中搜索单词,我使用以下代码: $searchthis = "Summerevent"; $matches = array(); $handle = @fopen("messages/20191110170912.txt", "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle); if(strp
messages
,里面有很多txt文件
要在.txt
文件中搜索单词,我使用以下代码:
$searchthis = "Summerevent";
$matches = array();
$handle = @fopen("messages/20191110170912.txt", "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $buffer;
}
fclose($handle);
}
//show results:
echo $matches[0];
这对于特定的.txt文件很有效
但是我如何在目录消息中的所有txt文件中搜索呢
第二个问题:显示找到字符串的txt文件的名称;比如:
您可以使用20191110170912.txt中的Summerevent查找文件。其中,$path
是指向邮件
目录的绝对路径
$path = '...';
$files = glob($path . '/*.txt');
foreach ($files as $file) {
// process your file, put your code here used for one file.
}
以下方面应起作用:
$searchthis = "Summerevent";
$matches = array();
$files = glob("messages/*.txt"); // Specify the file directory by extension (.txt)
foreach($files as $file) // Loop the files in our the directory
{
$handle = @fopen($file, "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $file; // The filename of the match, eg: messages/1.txt
}
fclose($handle);
}
}
//show results:
echo $matches[0];