Link to home
Start Free TrialLog in
Avatar of Rahul Sehrawat
Rahul Sehrawat

asked on

search for string in php files

Hi,

I am looking for php function which would search for a string(s) in all the PHP files in a specific directory (including subdirectories). If possible, If I can exclude the specific folder while searching. I would want the list of all files using specified string(s).

Any help / lead will be appreciated.

Thanks
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Does this have to be part of an application or is it separate? Will you need to repeat this process?
There are many tools for searching through files for specific strings or patterns - they differ based on the use-case.
Avatar of Rahul Sehrawat
Rahul Sehrawat

ASKER

I am actually creating a application. So it will be part of that. and yes, this process will be repeated time to time.

Thanks
Take a look at http://php.net/manual/de/class.directoryiterator.php 
Once you have a list of files you can iterate them and use http://php.net/manual/de/function.file-get-contents.php to search them for a term.

By the way, many editors have that functionality built in already.

Bye, Olaf.
You could do something like this
<?php
// FOLDER TO SEARCH IN
$target_folder  = "./";
// TEXT TO SEARCH FOR
$searchtext = 'in_array';

// CALL SEARCH FUNCTION
$res = doSearch($target_folder, $searchtext);

// DUMP RESULTS
echo "<pre>" . print_r($res, true) . "</pre>";


// RECURSIVE SEARCH FUNCTION
function doSearch($target, $searchtext) {
  $results = array();
  if (is_dir($target)) {
    if ($dh = opendir($target)) {      
      while(($file = readdir($dh)) != false) {
        if ($file == '.' || $file == '..') continue;
        if (is_dir($file)) {
          $subdir = "{$target}{$file}/";
          $results = array_merge($results, doSearch($subdir, $searchtext));
        }
        else {
          $ext = strtolower(end(explode('.', $file)));
          if ( $ext == 'php') {
            $path = $target . $file;
            if( strpos(file_get_contents($path),$searchtext) !== false) {
              $results[] = $path;
            }
          }
        }
      }
      closedir($dh);
    }
  }
  return $results;
}

Open in new window

Hi Julian,

Thanks for the function. I am only facing one issues with the function that when I set target as "../" it doesn't work.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Awesome. Works like a charm. :)
You are welcome.