0

私は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 ファイルにあります。検索ボックスに単語を入力すると、ページの本文全体が結果として表示され、特定の行または単語が必要です。コンテンツにない単語を入力しても。私のファイルの本体は、私がどこで間違いを犯したのかわからないことを示しています。

4

1 に答える 1

0

まず、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): 
?>
于 2013-03-27T05:22:53.930 に答える