我有一个 PHP 搜索脚本,我对其进行了轻微的修改,并且对我来说效果很好。但有一个部分我不确定该怎么做,即将脚本链接到用户可以完成的搜索表单。
脚本如下,它在文本文件中搜索关键字。目前,“关键字”直接输入到脚本中。但这对于访问我的网站的人来说没有什么好处 - 所以我想创建一个搜索表单。但不确定我是否应该使用 POST 或 GET 或其他方式。我不知道应该如何将代码从表单链接到下面的脚本。我已经搜索了相当多的时间来找到这个,但看不到任何涵盖它的内容,并且我尝试将其连接起来的尝试进展并不顺利。如果有人可以提供帮助,我们将不胜感激。
(从 Lekensteyn 借用的原始代码 - https://stackoverflow.com/a/3686246/1322744(感谢))
<?php
$file = 'users.txt';
$searchfor = 'entersearchterm';
$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);
}
?>
最佳答案
代码(粗略的想法):
<html>
<head><title>Search Form</title></head>
<body>
<form action="search.php" method="GET">
<input type="text" name="keyword" id="keyword width="50" value="" />
<input type="submit" value="Search"/>
</form>
</body>
</html>
并从 PHP 脚本中获取关键字,如下所示:
<?php
// script.php
$searchfor = $_GET['keyword'];
$file = 'users.txt';
$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);
}
?>
关于PHP:如何创建链接到我的搜索脚本的搜索表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10082607/