Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is my solution:<br></p> <pre><code>&lt;?php class FileGrep { private $dirs; // Scanned directories list private $files; // Found files list private $matches; // Matches list function __construct() { $this-&gt;dirs = array(); $this-&gt;files = array(); $this-&gt;matches = array(); } function findFiles($path, $recursive = TRUE) { $this-&gt;dirs[] = realpath($path); foreach (scandir($path) as $file) { if (($file != '.') &amp;&amp; ($file != '..')) { $fullname = realpath("{$path}/{$file}"); if (is_dir($fullname) &amp;&amp; !is_link($fullname) &amp;&amp; $recursive) { if (!in_array($fullname, $this-&gt;dirs)) { $this-&gt;findFiles($fullname, $recursive); } } else if (is_file($fullname)){ $this-&gt;files[] = $fullname; } } } return($this-&gt;files); } function searchFiles($pattern) { $this-&gt;matches = array(); foreach ($this-&gt;files as $file) { if ($contents = file_get_contents($file)) { if (preg_match($pattern, $contents, $matches) &gt; 0) { //echo $file."\n"; $this-&gt;matches = array_merge($this-&gt;matches, $matches); } } } return($this-&gt;matches); } } // Usage example: $fg = new FileGrep(); $files = $fg-&gt;findFiles('.'); // List all the files in current directory and its subdirectories $matches = $fg-&gt;searchFiles('/open/'); // Search for the "open" string in all those files ?&gt; &lt;html&gt; &lt;body&gt; &lt;pre&gt;&lt;?php print_r($matches) ?&gt;&lt;/pre&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Be aware that:<br></p> <ul> <li>It reads each file to search for the pattern, so it may require a lot of memory (check the "memory_limit" configuration in your PHP.INI file).</li> <li>It does'nt work with unicode files. If you are working with unicode files you should use the "mb_ereg_match" function rather than the "preg_match" function.</li> <li>It does'nt follow symbolic links</li> </ul> <p>In conclusion, even if it's not the most efficient solution at all, it should work.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload