用php如何读取多个TEXT文件并显示文件名?

问题描述 投票:0回答:2

我有一个PHP代码读取文本文件,允许用户搜索一个单词及其工作完美。

文件内容是阿拉伯语

在用户进行搜索的情况下,系统将显示所请求的字符串及其存在的行号。

我现在想要的是让系统读取多个文本文件,当用户请求一个单词时,系统将显示他找到用户请求的文件的名称。

这有可能,如果我有100个文件,这个过程需要多长时间?

code:

<?php

$myFile = "arabic text.txt";

$myFileLink = fopen($myFile, 'r');

$line = 1; 

if(isset($_POST["search"]))
{
    $search =$_POST['name'];

 while(!feof($myFileLink)) 
 { 
     $myFileContents = fgets($myFileLink);
     if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches))
     {

        foreach($matches[1] as $match)
        {
           echo "Found $match on Line $line";
        }

     }

     ++$line;

 }

}

fclose($myFileLink);

//echo $myFileContents; 
?>

<html>
    <head>
    </head>
    <meta http-equiv="Content-Language" content="ar-sa">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <body>
     <form action="index.php" method="post">
          <p>enter your string <input type ="text"  id = "idName"  name="name" /></p>
          <p><input type ="Submit" name ="search" value= "Search" /></p>
    </form>
    </body>
</html>
php preg-match-all readfile
2个回答
0
投票

因此,您必须将当前正在运行的代码放入一个函数中,该函数返回您想要的内容。

function readFile($fileName)
{
  // ...your code
  return $yourMessage;
}

$fileNames = array("file1.txt", "file2.txt");
$result = array();
foreach($fileNames as $name)
{
  $message = readFile($name);
  $result[$name] = $message;
}

您现在可以迭代$ result并以您想要的方式打印它。


0
投票

要将所有文件放入一个数组,可以使用scandir('/ mydir /')。

$files = scandir('/mydir/here/');
foreach($files as $file) {
    if (strpos($file, '.txt')) {
        //dosomething
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.