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 do not know how to do this. I've had Googled for quite some time, and I haven't found anything. So I ask you guys, how can I fix this?

Thanks in advance.

+7
source share
4 answers

You can get what you need without using grep. Grep is a convenient tool when you are on the command line, but you can do what you need with just a little PHP code.

This small snippet, for example, gives 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; } } } 
+5
source

If this is the Unix host you are running on, you can make a grep system call 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 
+10
source

If you use Linux, you can grep instead of using PHP. In particular, for php, you can iterate over files in a directory , open each as a line , find the line and save the file if the line exists.

+3
source

Just provide a file name, get the contents of the file, and combine the regular expression with the contents of the file. See this and this for more information about my sample code 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 regardless of whether you are in a Linux window.

+1
source

All Articles