Searching a name in a file txt using PHP
我正在尝试创建一个搜索功能来搜索包含在 txt 文件中的数据中的名称。
我有这样的数据:
1 2 3 4 | dimitri, 1998, php nikolai, 1998, php yuri, 1998, php alyosha, 1998, php |
我想出了一个想法,将这些数据更改为这样的数组:
1 2 3 4 5 6 7 | Array ( [0] => dimitri, 1998, php [1] => nikolai, 1998, php [2] => yuri, 1998, php [3] => alyosha, 1998, php ) |
然后再分割成多维
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
这样我就可以通过key搜索名字了。
现在我不知道该怎么办了。我尝试使用
试图
1 2 3 4 5 6 7 8 9 10 11 12 | $array = array(); $split = explode('\ ', file_get_contents($file)); foreach ($split as $content){ $array = array_filter(array_map("trim", explode("\ ", $content))); $array1 = array(); $split2 = explode(",", $array); foreach($array as $row){ $array1[$row[1]][$row[2]][]=$row[0]; } } |
HTML
1 2 3 4 | <form action="search.php" method="POST"> <input name="search_function" type="text" placeholder="Search who you want"> <input type="submit" name="search" value="Search"> </form> |
关于我的搜索,我想使用 post,如果在搜索输入中正确输入数据,数据将显示。
你的文件似乎是 CSV 格式(或者至少它的内容是),所以考虑这段代码:
它将把你的文件转换成一个数组。
https://www.php.net/manual/fr/function.file.php
https://www.php.net/manual/fr/function.str-getcsv.php
你可以试试下面的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | /* read data from text file, line by line */ $arr = []; // file contents go into this array $handle = fopen('test.txt', 'r'); if ($handle) { while (($line = fgets($handle)) !== false) { $arr[] = explode(',', $line); } fclose($handle); } else { echo 'error occured'; } /* echo the form */ $form = <<<HEREDOC <form action="#" method="POST"> <input name="search_function" type="text" placeholder="Search who you want"> <input type="submit" name="search" value="Search"> </form> HEREDOC; echo $form; /* the search logic */ $found = false; $count = 0; // count # of hits if(isset($_POST['search'])) { foreach($arr as $key => $value) { foreach ($value as $key => $value) { if ($value == $_POST['search_function']) { $count++; $found = true; break 2; } } } } /* result */ $message = ($found === true) ?"found" . $_POST['search_function'] ." (" . $count .") occurrence." : 'nothing found.'; echo $message; |
还有一个PHP例子,会显示多条匹配的行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php $file = 'somefile.txt'; $searchfor = 'name'; // the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain'); // 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, '/'); // finalise the regular expression, matching the whole line $pattern ="/^.*$pattern.*\\$/m"; // search, and store all matching occurences in $matches if(preg_match_all($pattern, $contents, $matches)){ echo"Found matches:\ "; echo implode("\ ", $matches[0]); } else{ echo"No matches found"; } |