需要帮助在Php中创建搜索框


Need help in creating search box in Php

我刚刚开始学习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文件中。如果我在搜索框中输入一个单词,整个页面就会出现,因为我需要特定的一行或其中的单词。甚至我键入一个词,这是不存在于我的内容它。我的文件主体显示我不知道我在哪里出错了谁能指点我一下吗

首先,你的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): 
?>