AAA
AAA

Reputation: 2032

How do I search a file and return an array of the results and line number in PHP?

How do I search a file and return an array of the results so that I can use it in a collection in PHP?

So, for example, say I have a .txt file with something like:

hellohello
hihi
heywhats up
hello hey whats up
hello

And I want to search for all occurrences with hello and its line number, then return it as an array so I can use it in a data collector.

So, it would return the line number and line, like:

$results = array
(
array('1', 'hellohello'), 
array('4', 'hello hey whats up'), 
array('5', 'hello'),
);

My idea is to us file_get_contents.

So, for example..

$file = 'example.txt';

function get_file($file) {
  $file = file_get_contents($file);
  return $file;
}

function searchFile($search_str) {
  $matches = preg_match('/$search_str/i', get_file($file);
  return $matches;
}

Upvotes: 3

Views: 347

Answers (1)

Kevin
Kevin

Reputation: 41885

As an alternative, you could also use file() function so it reads the entire file into an array. Then you could just loop, then search. Rough example:

$file = 'example.txt';
$search = 'hello';
$results = array();
$contents = file($file);
foreach($contents as $line => $text) {
    if(stripos($text, $search) !== false) {
        $results[] = array($line+1, $text);
    }
}
print_r($results);

Sidenote: stripos() is just an example, you could still use your other way/preference to search the needle for that particular line.

Upvotes: 2

Related Questions