-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathresults.php
68 lines (50 loc) · 1.66 KB
/
results.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<a href="search.html">Back</a><br>
<?php
// function to clean up the userinput
function cleanSearchTerms($arg) {
return explode(" ", preg_replace("/[^a-zA-Z0-9]+/", " ", strtolower(trim($arg))));
}
// function to check if string containts all items in a list
function contains_all($str,array $words) {
if(!is_string($str))
{ return false; }
foreach($words as $word) {
if(!is_string($word) || stripos($str,$word)===false)
{ return false; }
}
return true;
}
//convert user input into an array of clean search terms
$searchQuery = $_POST["searchQuery"];
$searchTerms= cleanSearchTerms($searchQuery);
usort($searchTerms, function($a, $b) {return strlen($b) <=> strlen($a);}); //Sort searchTerms on lenght to perform search faster
//read text file
$lines = file('merged.txt');
//show info about search query and txt
echo count($lines) . " links in the database <br> You searched for " . $searchQuery . "<br>";
//Saveing timestamp for later
$timeBeforeSearch = microtime(true);
//search for matches
$searchResults = array();
foreach($lines as $line)
{
if(contains_all($line, $searchTerms))
{
array_push($searchResults, $line);
}
}
//Calculate how long searching took
$searchingTime = round((microtime(true) - $timeBeforeSearch),2) ;
//show results
echo count($searchResults) . " links found in " . $searchingTime . " seconds<br>";
echo "<ol>";
foreach($searchResults as $result)
{
echo "<li><a href='".$result."'>$result</a></li><br>";
}
echo "</ol>";
// If the text was not found, show a message
if (empty($searchResults))
{
echo 'No match found';
}