Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for phrase/word in text files with php

How would I scan a directory for a specific line of text and list all matching files with php?

Thanks.

like image 847
usertest Avatar asked Feb 28 '10 18:02

usertest


2 Answers

I actually wrote a function for this a few days ago...

Here's the base function that scans each file...

foreach (glob("<directory>/*.txt") as $search) {
    $contents = file_get_contents($search);
    if (!strpos($contents, "text")) continue;
    $matches[] = $search;
}

Not the most advanced way of doing it, my function is much longer but it also uses all functions from my various other classes, this is basically what it does though.

like image 103
animuson Avatar answered Sep 28 '22 23:09

animuson


An alternative is to read the php files, put the content into arrays and use something like preg_grep.

If the number of files is potentially very big, you might want to use the UNIX grep command together with a php exec.

I would personally go for the second solution.

like image 30
Roberto Aloi Avatar answered Sep 29 '22 00:09

Roberto Aloi