0

I am trying to use PHP to get an array of all of the filenames within a directory that match any strings in an array.

The array of strings to search looks like this:

$users = array('user1', 'user2', 'user3');

What I am hoping to get is a list of files matching any of these strings back in an array like this:

$files = array('user1_resume.pdf', 'user1_statement.pdf', 'user2_resume.pdf');

How should I do this in PHP?

6
  • Are you looking for exact matches only? Commented Jul 14, 2015 at 18:45
  • This question is a little short on information. Can you share what you have tried, and what problems you have run into? Commented Jul 14, 2015 at 18:46
  • @Anonymous no I am not. Results like if I did ls user1* user2* user3* Commented Jul 14, 2015 at 18:46
  • php.net/preg_grep php.net/foreach Commented Jul 14, 2015 at 18:50
  • php.net/manual/en/function.glob.php Commented Jul 14, 2015 at 18:51

2 Answers 2

1

Use the function glob.

$users = array('user1', 'user2', 'user3');
$searchString = implode(',',$users);
$result = glob('*{' . $searchString . '}*',GLOB_BRACE);
print_r($result);

http://php.net/manual/en/function.glob.php

Quote from source above:

GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'

[Edit]

If the filename must start with whatever is in your list of users just remove the first asterix in the example above.

Sign up to request clarification or add additional context in comments.

2 Comments

It also needs to be in a specific directory. Would this work fine with this method: glob('html/upload' . '{' . $searchString . '}*',GLOB_BRACE);
That would work fine with a little bit of change in your code, because you forgot one slash. You can even skip the delimiter you're using for the braces. glob('html/upload/{' . $searchString . '}*',GLOB_BRACE);
1

Try this. It's not most efficient solution but it's clear

$users = array('user1', 'user2', 'user3');
$files = array('user1_resume.pdf', 'user1_statement.pdf', 'user2_resume.pdf');


// to read from directory
//$files = scandir($dirName);



$resultFiles = array();
foreach($files as $file){
 foreach($users as $user){
    if(strpos($file,$user) !== null)
        $resultFiles[] = $file;
 }
}

echo "array:" .print_r( array_unique($resultFiles), true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.