Click to See Complete Forum and Search --> : String search CLI script


KrisG
07-29-2005, 06:01 PM
Hello,

This program, thanks to a great tip from someone over in the Coding forum, searches each file by each of the keywords. If the keyword is found in the file it writes to a text file. If none of the keywords are found it writes to a different text file. The program runs great, but it is a little slow. I estimated it took about 20-30 seconds for each file it searched. Any alternative suggestions are greatly appreciated!!


$key = file("changes.txt"); //text file containing keywords
$file = file("sqrs.txt"); //text file containing filenames to index
$counter = count($key);
$i = 0;

foreach ($file as $files)
{
$files = trim($files);
$filecontents = file_get_contents($files);

foreach ($key as $keys)
{
$found = false;
$keys = trim($keys);
if (stristr($filecontents, $keys))
{
$i = 0;
$found = true;
$content = $keys . " was found in file " . $files . "\r\n";
$filec = fopen("output1.txt", "a+");
fwrite($filec, $content);
fclose($filec);
}
elseif ($found == false) {
$i++;
if ($i == $counter) {
$content = $files . " is clean.\r\n";
$filec = fopen("output2.txt", "a+");
fwrite($filec, $content);
fclose($filec);
continue 2; } } } }

Thank you,
KrisG.

Weedpacket
07-30-2005, 05:47 AM
One clear speedup would be to append all of your results to the output files at once; or at least open the files once at the start and close them at the end. Rather than the current approach of open a file, write one item to it, close the file, open the file, write one item to it, close the file,... (repeat (number of keywords)*(number of files) times).

mrhappiness
08-01-2005, 04:07 AM
Why not doing sth. like this?$pattern = '%('.implode('|', array_map('preg_quote', $keywords)).')%i';

preg_match_all($pattern, $file, $matches);

$matches = array_unique(array_map('strtolower', $matches[0]));