Home » Php » Find specific text in multiple TXT files in PHP

Find specific text in multiple TXT files in PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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;
    }
  }
}

Answer:

If it is a Unix host you’re running on, you can make a system call to grep in the directory:

$search_pattern = "text to find";
$output = array();
$result = exec("/path/to/grep -l " . escapeshellarg($search_pattern) . " /path/to/directory/*", $output);

print_r($output);
// Prints a list of filenames containing the pattern

Answer:

If you’re on a linux box, you can grep instead of using PHP. For php specifically, you can iterate over the files in a directory, open each as a string, find the string, and save the file if the string exists.

Answer:

Just specify a file name, get the contents of the file, and do regex matching against the file contents. See this and this for further details regarding my code sample below:

    $fileName = '/path/to/file.txt';
    $fileContents = file_get_contents($fileName);
    $searchStr = 'I want to find this exact string in the file contents';

    if ($fileContents) {  // file was retrieved successfully

        // do the regex matching
        $matchCount = preg_match_all($searchStr, $fileContents, $matches);

        if ($matchCount) {  // there were matches
            // $match[0] will contain the entire string that was matched
            // $matches[1..n] will contain the match substrings    
        }

    } else {  // file retrieval had problems

    }

Note: This will work irrespective of whether or not you’re on a linux box.