Eli
Eli

Reputation: 4359

preg_match exact word and print out the entire line the result was found in

i'm having a hard time understanding how to do this.

I want to search for a word, and then I want the search to return the word along with all the contents on the line the word was found in.

The word needs to be case sensitive so searching for TOM will not return Tom along with the results.

this is what I have tried thus far.

$contents = file_get_contents($file);
$pattern = preg_quote($word, '/');
$numInt  = 0;
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches))
{
    $numInt = count($matches[0]);
}

When I run this through my function it returns the results I want, but I noticed that it isn't consistant across different keyword.

In my text file for testing I have INT (x18) and my function returns 18 as the count. But if I use the keyword MORNING (x29) the function returns 31 which is technically correct because there are 2 instances where morning is used.

Upvotes: 0

Views: 2156

Answers (1)

Jason
Jason

Reputation: 15378

Well you could avoid using regex all together for this task.

Here's some code I whipped up:

<?php 
$contents = file_get_contents($file);

#standardise those line endings
$contents = str_replace(array("\r","\r\n","\n\r","\n"),"\n",$contents);
$lines = explode("\n", $contents);

#find your result
$result = $line_num = array();
foreach($lines as $line_num => $l)
  if(strpos($l, $word)) {
   $result[] = $l;
   $line_nums[] = $line_num;
  }

echo "<pre>";
print_r($result);
echo "<br>Count:".count($result);

Upvotes: 2

Related Questions