【问题标题】:Need help in creating search box in Php需要帮助在 PHP 中创建搜索框
【发布时间】:2013-03-27 04:17:35
【问题描述】:

我刚刚开始学习php几个弱点之前..我正在研究一个搜索框但我无法得到结果

  <html>
  <head><title>Search Form</title></head>
  <body>
        <form action="12.html" method="GET">
               <input type="text" name="keyword" id="keyword width="50" value="" />
               <input type="submit" value="Search"/>
  </form>
  </body>
  </html>
  <?php
  $searchfor = $_GET['keyword'];
  $file = '12.html';
  $contents = file_get_contents($file);
  $pattern = preg_quote($searchfor, '/');
  $pattern = "/^.*$pattern.*\$/m";
  if(preg_match_all($pattern, $contents, $matches)){
  echo "Found matches:<br />";
  echo implode("<br />", $matches[0]);
  }
  else{
  echo "No matches found";
  fclose ($file); 
  }
  ?>

我的搜索内容在 12.html 文件中。如果我在搜索框中键入单词,我的页面的整个正文就会出现,因为结果我需要特定的行或其中的单词。即使我输入了我的内容中不存在的单词。我的文件正文显示我不知道我在哪里做错了任何人都可以指导我。

【问题讨论】:

  • 您的表单将转到 12.html,而实际上它应该转到您所在的当前 PHP 页面。将操作更改为“whateverthispageiscall.php”,然后测试?

标签: php html search-box


【解决方案1】:

首先,您的 HTML 语法存在错误。您希望操作指向您的脚本。

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">

您的输入项有错误。

<input type="text" name="keyword" id="keyword" width="50" value="" />


<?php
$searchfor = $_GET['keyword'];
$file = '12.html';
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = '/'.$pattern.'/m';
if(preg_match_all($pattern, $contents, $matches)){
    echo "Found " . count($matches) . " matches:<br />";
//here you are imploding the entire array;
    echo implode("<br />", $matches);
}
else{
    echo "No matches found";
    fclose ($file); 
}
?>

我不明白您为什么要内爆匹配项,因为这只会列出相同的单词,无论它被找到多少次。如果你想找到具体的线路,你可以试试这个。

<?php
$lines = explode('\n',$contents);
$lineNum = 1;
$linesFound = array();
foreach ($lines as $line){
    if (preg_match($pattern, $line)){
        $linesFound[] = $lineNum;
    }
    $lineNum++
}
if (!empty($linesFound)){
}
echo "Keyword found on line(s): 
?>

【讨论】:

  • 它不工作它重定向到我的 12.html 文件本身没有显示我正在搜索的关键字
猜你喜欢
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
  • 2012-08-25
  • 2017-11-08
  • 2017-08-03
相关资源
最近更新 更多