I am doing a mini search system for urls that are stored in a .txt file, one per line, my problem is the performance issue because I have 5000 urls stored (only) and it is already slow in the search , on the server side I have:
if(isset($_GET['search'])) {
$urls = array();
if(trim($_GET['search']) != '') {
$urls = search_in_urls($_GET['search']);
}
echo json_encode($urls);
}
function search_in_urls($search) {
$file = fopen("urls.txt", "r");
$urls = array();
while(!feof($file)){
$url = fgets($file);
if (strpos($url, $search) !== false) {
$urls[] = $url;
}
}
return $urls;
}
I saw this response accepted in SOen and would like to implement it, but how to return all lines where a match is recognized with my $search
?
The search solution I saw and would like (unless there are better options) to implement was:
if(exec('grep '.escapeshellarg($search).' ./urls.txt')) {
// do stuff
}
That is, is there any way I can not go through all the lines looking for a match (set of chars like the one I wrote) and return that corresponding line in full? Or at least to make this search much faster?