Erik Edgren Erik Edgren - 5 months ago 9
PHP Question

Find specific text in multiple TXT files in PHP

I want to find a specific text string in one or more text files in a directory, but I don't know how. I have Googled quite a long time now and I haven't found anything. Therefor I'm asking you guys how I can fix this?

Thanks in advance.

Answer

You can get what you need without the use of grep. Grep is a handy tool for when you are on the commandline but you can do what you need with just a bit of PHP code.

This little snippet for example, gives you results similar to grep:

$path_to_check = '';
$needle = 'match';

foreach(glob($path_to_check . '*.txt') as $filename)
{
  foreach(file($filename) as $fli=>$fl)
  {
    if(strpos($fl, $needle)!==false)
    {
      echo $filename . ' on line ' . ($fli+1) . ': ' . $fl;
    }
  }
}
Comments