Jake Simpson
Jake Simpson

Reputation: 51

Finding files with a certain string

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.

Upvotes: 5

Views: 11996

Answers (3)

Faisal Shaikh
Faisal Shaikh

Reputation: 4138

I found a small file to search the string from folder:

Download file from here.

Upvotes: 2

Tigger
Tigger

Reputation: 9130

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.

Upvotes: 3

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

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

Upvotes: 11

Related Questions