回声结果进入循环


Echo result goes in loop

我有一个html搜索框,它使用下面的脚本,但echo输出似乎是循环的,或者显示.txt文件中的所有结果,您可以看到我正在使用fopen。我试图在echo的末尾添加exit,但无论我使用搜索框搜索什么,它都只能获得content.txt中的第一行。我试图让它只显示搜索的结果。

这是我一直在研究的代码:

<?php
$q = $_REQUEST["q"];
$f = fopen("content.txt", "r");
while (($line = fgets($f)) !== FALSE) {
    if (strstr($line, $q)) {
        echo "<li>Found $line</li>";
    } else {
        echo "<p>Nothing found.</p>";
    }
}
?>

像这样尝试

<?php
    $q = $_REQUEST["q"];
    $f = fopen("test.txt", "r");
    $found = false;
    while (($line = fgets($f)) !== FALSE) {
        if (strstr($line, $q)) {
            echo "<li>Found $line</li>";
            $found = true;
        }
    }
    if (!$found){
        echo "<p>Nothing found.</p>";
    }
?>

PHP有一个用于模式搜索的内置函数。你可以在这里找到答案。PHP在txt文件中搜索并回显整行

由于您正在尝试获取文本文件中找到的所有结果,请创建一个空白字符串,如果结果存在,则将其连接到循环中,echo the result else the no result found。

<?php
$str='';
$q = $_REQUEST["q"];
$f = fopen("content.txt", "r");
while (($line = fgets($f)) !== FALSE) {
    if (strstr($line, $q)) {
        $str.="<li>Found $line</li>";
    }
}
if($str==''){
    echo "<p>Nothing found.</p>";
}else {
   echo $str;
}
?>