0

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?

user1547410
  • 863
  • 7
  • 27
  • 58
  • Just so I don't jump the gun with a solution, before I do. Could you show an example of the string you are searching? and the params you are putting into your stripos? – Daryl Gill Apr 10 '13 at 00:30

2 Answers2

1

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

Community
  • 1
  • 1
jszobody
  • 28,495
  • 6
  • 61
  • 72
  • I do not see the downside to a solution like this, it seems like a logical solution for something like this – Daryl Gill Apr 10 '13 at 00:37
-1

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

$pos = stripos($body,$keyword,$offset);
  • How does a negative offset work, can i just set -1 and it starts from the end? – user1547410 Apr 10 '13 at 07:12
  • With a negative offset the search will start from that many characters from the end of the string. So a -1 offset will start searching one character from the end of the string. Even though the search is backwards the return value will still be relative to the beginning of the string. – user1613098 Apr 10 '13 at 14:30