从dat文件中查看我在php中的搜索,这是我目前的代码:
<?php
if (isset($_POST["name"]))
{
$file = 'order.dat';
$searchfor = $_POST["name"];
// the following line prevents the browser from parsing this as HTML.
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
//$pattern = "/^$pattern/m"; // your string starts with $pattern (177)
$pattern = "/^$pattern.*$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
}
?>
<h3>Search Order Details</h3>
<form method="post" action="search.php" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
order.dat文件包含: -
175|RC456456456|54156456177|177$
176|RC456456177|54156456177|177$
177|RC456456177|54156456465|129$
178|RC456456456|54156456177|177$
现在现在如果找到搜索然后它说找到匹配...就像我输入177给它
Found matches: 177|RC456456177|54156456465|129$
现在,如果我输入002,则表示找不到匹配项
如果搜索匹配,我想在此表格中显示: -
<table>
<tr>
<th>Order number </th>
<th>Tranasaction id</th>
<th>Date </th>
<th>Total Price</th>
</tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</table>
答案 0 :(得分:1)
您必须使用fopen
或file_get_contents
打开文件,然后在换行符explode
或split
上\n
或\r\n
(取决于操作系统和文件)。
然后,您可以循环遍历它们并再次explode
该字符串,以查看第一个元素是否是您要查找的内容。像这样:
$resLines = explode("\n", $FileContents);
foreach ($resLines as $line) {
$resLine = explode("|", $line);
if ($resLine[0] == $Search) {
echo "Found! $line";
}
}
有关您的修改的更新
这将是这样的:
$resContents = file_get_contents("order.dat");
$resLines = explode("\n", $FileContents);
foreach ($resLines as $line) {
$resLine = explode("|", $line);
if ($resLine[0] == $Search) {
$aFound = $resLine; // setting our array with the found contents
}
}
echo "
<table>
<tr>
<th>Order number </th>
<th>Tranasaction id</th>
<th>Date </th>
<th>Total Price</th>
</tr>
<tr>
<td>" . $aFound[0] . "</td>
<td>" . $aFound[1] . "</td>
<td>" . $aFound[2] . "</td>
<td>" . $aFound[3] . "</td>
</tr>
</table>";