Hi,
I created the class because I found your code quite difficult to read and understand - was quicker for me to write the class - it should be quite easy to take the class and implement it in place of your code (stick the class in a separate file and include it) - will make your code much easier, and hey its all part of the learning process, right?
In answer to your specific question, take a look at the following functions from the class.
For looping through lines of a given file (looping through files in a given directory and looping through directories recursively is handled elsewhere):
PHP Code:
function searchFileForString($file)
{
// open file to an array
$fileLines = file($file);
// loop through lines and look for search term
$lineNumber = 1;
foreach($fileLines as $line) {
$searchCount = substr_count($line, $this->_searchString);
if($searchCount > 0) {
// log result
$this->addResult($file, $line, $lineNumber, $searchCount);
}
$lineNumber++;
}
}
Note that I create a variable $lineNumber which increments as I loop through each line in the file - I can use this variable to log the line number when I call the addResult() function (which saves a match to an array). That's the first part dealt with - saving the line number along with each search result (note that I also save the contents of the line too, as well as the file name/path and the number of times the search term was found on that line (in case it is repeated more than once in a given line).
In my presentation code (the "example usage" above), when I loop through the search results using foreach:
Code:
foreach($searcher->getResults() as $result)
...
, the resulting $result variable is a multidimentional array representing one result, with the following data available: filePath, lineContents, lineNumber, searchCount. Use $result['lineNumber'] to print out the line number. Use $result['lineContents'] to simply print out the contents of the line.
And now the bit relating to highlighting the search term...instead of just displaying $result['lineContents'], pass it into the class function highlightSearchTerm(). This will highlight the search term each time it appears on the line.
The simple bit of code which does that is this:
PHP Code:
str_replace($this->_searchString,
'<strong>'.$this->_searchString.'</strong>',
$string);
Hope that explains things better.
__________________