我有一个PHP代码,它读取多个txt文件并搜索单词的用户请求,如果该单词存在,代码将显示带有行号和文件名的请求单词。
代码工作正常,但问题在于行号,因为系统将所有txt文件合并到一个文件中并继续计算行号。
我想要的是让系统从每个文件的第一行开始
示例:
wordمحلي存在于同一行13的7个文件中 系统显示:
然而,第13行的所有这些文件都存在这个词
<?php
$line = 1;
if(isset($_POST["search"]))
{
$search =$_POST['name'];
foreach(glob($_SERVER['DOCUMENT_ROOT']."/readfiletest/*.txt") as $txts)
{
$myFileLink = fopen($txts, 'r');
while(!feof($myFileLink))
{
$myFileContents = fgets($myFileLink);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches))
{
foreach($matches[1] as $match)
{
echo "the word $match exist on line [$line] in ";
}
echo basename ($txts) . "<br>".PHP_EOL;
//++$line;
}
++$line;
}
fclose($myFileLink);
}
}
?>
<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>
答案 0 :(得分:0)
将您的PHP代码更改为此。希望这会有所帮助。
<?php
$line = 1;
if(isset($_POST["search"]))
{
$search =$_POST['name'];
echo "the word $search exist on <br><br>";
foreach(glob($_SERVER['DOCUMENT_ROOT']."/readfiletest/*.txt") as $txts)
{
$myFileLink = fopen($txts, 'r');
while(!feof($myFileLink))
{
$files[] = basename($txts);
$myFileContents = fgets($myFileLink);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches))
{
foreach($matches[1] as $match)
{
//echo "line [$line] in ";
$lines[str_replace(" ", "_", basename($txts))][] = $line;
}
//echo basename($txts) . "<br>".PHP_EOL;
}
++$line;
}
fclose($myFileLink);
}
}
?>
并在正文中添加此
<?php if(isset($_POST["search"]) && !empty($files)): ?>
<table border="1">
<thead>
<tr>
<td>File Name</td>
<td>Line No.</td>
</tr>
</thead>
<tbody>
<tr>
<?php foreach ($files as $name): ?>
<td><?= $name; ?></td>
<td><?= implode(', ', $lines[str_replace(" ", "_", $name)]); ?></td>
<?php endforeach ?>
</tr>
</tbody>
</table>
<?php endif; ?>