Question

I have some code that searches a huge log file and finds a keyword, for the majority of cases this is near the bottom of the document. It would be more efficient in this case to start my search at the bottom and work my way up.

$pos = stripos($body,$keyword);  
$snippet_pre = substr($body, $pos, SNIPPET_LENGTH);

I've looked at strripos and although it does what i want as in find the last occurrence it sounds like it searches from the beginning of the document so ill be adding a lot of unnecessary work to my query as most of the keywords are near the bottom of the string/document

Any ideas?

Was it helpful?

Solution

Explode your log file by linebreaks to get an array. Reverse your array, and now you can search line by line from the end.

$lines = explode("\n",$body);
$reversed = array_reverse($lines);
foreach($reversed AS $line) {
   // Search for your keyword
}

If you are talking about a massive log file, such that you absolutely do not want to read it all into memory, you could also look at a reverse seek approach, though that's typically not needed. See here:

Read a file backwards line by line using fseek

OTHER TIPS

strripos will start from the end and search backwards if you set a negative offset as the third parameter.

$pos = stripos($body,$keyword,$offset);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top