如果搜索在php中匹配,则在表中显示 [英] Display in the table if search matches in php
问题描述
请参阅从dat文件在php中搜索我的内容,到目前为止,这是我的代码:
see my Search in php from dat file, This is my code so far:
<?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文件包含:-
order.dat file contains:-
175|RC456456456|54156456177|177$
176|RC456456177|54156456177|177$
177|RC456456177|54156456465|129$
178|RC456456456|54156456177|177$
现在现在如果找到搜索,则说找到匹配项...就像我输入177一样,
Found matches: 177|RC456456177|54156456465|129$
now right now if search is found then it says Found matches ... like if i enter 177 the it gives
Found matches: 177|RC456456177|54156456465|129$
现在,如果我输入002,则提示找不到匹配项
now if i enter 002 then it says No matches found
如果搜索匹配,我想在此表中显示:-
I want to Display in this table if search matches :-
<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>
推荐答案
您必须使用fopen
或file_get_contents
打开文件,然后在换行符\n
或\r\n
(取决于操作系统和文件).
You would have to open the file using fopen
or file_get_contents
, then you would explode
or split
on newlines \n
or \r\n
(depending on OS and file).
然后,您可以遍历它们并再次explode
该字符串以查看第一个元素是否是您要查找的内容.像这样:
Then, you could loop through them and explode
that string again to see if the first element is what you are looking for. Like so:
$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>";
这篇关于如果搜索在php中匹配,则在表中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!