Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding files with a certain string

Tags:

php

unix

windows

I'm a real noob here. I was wondering if anyone could give me a piece of code that will find all files in a certain directory and that directory's subdirectories with the user-specified string. And if possible limit filetypes to be searched e.g. *.php

I'm 99% it's possible maybe using RecursiveDirectoryIterator, preg_match or GLOB but i'm really new to php and have next-to-no knowledge on these functions.

This kind of code is certainly easy to do with UNIX commands but PHP i'm kind of stuck (need PHP not unix solutions). Would appreciate all and every help I can get from you guys!

EDIT: Seems i might have confused some of you. I want that string to be INSIDE the file not to be in the FILENAME.

like image 330
Jake Simpson Avatar asked Jan 13 '13 08:01

Jake Simpson


2 Answers

You can accomplish this pretty easily.

// string to search in a filename.
$searchString = 'myFile';

// all files in my/dir with the extension 
// .php 
$files = glob('my/dir/*.php');

// array populated with files found 
// containing the search string.
$filesFound = array();

// iterate through the files and determine 
// if the filename contains the search string.
foreach($files as $file) {
    $name = pathinfo($file, PATHINFO_FILENAME);

    // determines if the search string is in the filename.
    if(strpos(strtolower($name), strtolower($searchString))) {
         $filesFound[] = $file;
    } 
}

// output the results.
print_r($filesFound);
like image 94
Austin Brunkhorst Avatar answered Sep 21 '22 19:09

Austin Brunkhorst


Only tested on FreeBSD...

Find string within all files from a passed directory (*nix only):

<?php

$searchDir = './';
$searchString = 'a test';

$result = shell_exec('grep -Ri "'.$searchString.'" '.$searchDir);

echo '<pre>'.$result.'</pre>';

?>

Find string within all files from a passed directory using only PHP (not recommended on a large list of files):

<?php

$searchDir = './';
$searchExtList = array('.php','.html');
$searchString = 'a test';

$allFiles = everythingFrom($searchDir,$searchExtList,$searchString);

var_dump($allFiles);

function everythingFrom($baseDir,$extList,$searchStr) {
    $ob = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseDir), RecursiveIteratorIterator::SELF_FIRST);
    foreach($ob as $name => $object){
        if (is_file($name)) {
            foreach($extList as $k => $ext) {
                if (substr($name,(strlen($ext) * -1)) == $ext) {
                    $tmp = file_get_contents($name);
                    if (strpos($tmp,$searchStr) !== false) {
                        $files[] = $name;
                    }
                }
            }
        }
    }
    return $files;
}
?>

Edit: Corrections based on more details.

like image 32
Tigger Avatar answered Sep 19 '22 19:09

Tigger