PHP:在文件中搜索文本时出现问题

时间:2012-03-25 00:30:28

标签: php

我认为我做到这一点已经中途完成了半途而废。无论如何,以下代码可以在第一行找到它,但我有一个脚本可以在单独的行上创建每个代码。 请修改或创建以下全新版本,以便在每一行搜索表单数据。

$search = $_POST['search'];
$file = file("SLIST.txt");
foreach($file as $line) 
{
    $line = trim($line);
    if($line == $search) 
    {
        echo $search . " WAS found in the database";
    }
    else 
    {
        echo $search . " was NOT found in the database";
    }
}

表单我的意思是在上一页有一个搜索表单。此页面是告诉您放入搜索表单的文本是否与文件中的行匹配的页面(例如:第1行:BOOT第2行:树搜索条目:树回显消息:在数据库中找到树WAS。)< / p>

它目前无法像我预期的那样工作。

3 个答案:

答案 0 :(得分:1)

目前尚不清楚。我想以下是你想要的。

<?php
$search = $_POST['search'];
$file = file("SLIST.txt");
$found = false;
foreach($file as $line) {
  $line = trim($line);
  if($line == $search) {
    $found = true;
    break;
  }
}

if ($found)
{
  echo $search . " WAS found in the database";
}
else {
  echo $search . " was NOT found in the database";
}
?>

答案 1 :(得分:1)

如果您只想知道搜索字符串是否在文件中,并且不关心哪一行,则strpos()docfile_get_contents()可能适合您像这样:

$file = file_get_contents('SLIST.txt');
$search = $_POST['search'];

if (strpos($file,$search)){
    echo $search . " WAS found in the database";
}
else 
{
    echo $search . " was NOT found in the database";
}

如果您想了解该行,如果您使用if($line == $search)更改strpos(),您的解决方案也应该有效。

如果该行必须完全您正在寻找的搜索查询,那么您的解决方案应该可以正常工作

答案 2 :(得分:0)

您是否希望在整个文件中找到单个字符串。我知道你想看看每一条线,但这更有效率。 试试这个

 $file = file_get_contents("SLIST.txt");
if(strpos($file, $search)) 
{
 echo $search . " WAS found in the database";
}
 else {
  echo $search . " was NOT found in the database";
} 

如果您只想阅读行,请执行

if(strpos($line, $search))
{
 echo "found";

}
else 
{
 echo "not found";
}
相关问题