Search code examples
phpsearchdirectoryglob

Directory searching in PHP with multiple criteria


I've been trying to find a way to search a directory with multiple criteria in PHP with little luck.

I have a folder that contains multiple versions of the same file but in different languages and for different devices:

e.g.

 1. file_en_v980.jar

 2. file_fr_v980.jar

 3. file_en_v990.jar

 4. file_fr_v990.jar

I want to be able to search the directory for all English (en) .jar files for the v980.

I've tried this:

foreach(glob('./'.$installer_location.'/'.$brand_name.'/*en*.jar') as $filename){
    echo $filename."</br>";
}  

It works, but returns the french (fr) file too.

I've tried this:

foreach(glob('./'.$installer_location.'/'.$brand_name.'/*en,v980*.jar') as $filename){
    echo $filename."</br>";
} 

But it returns nothing so I'm assuming I've got the syntax wrong.

Any help would be greatly appreciated.

Addition:

Based on the suggestion from the comment below I tried this:

foreach(glob('./'.$installer_location.'/'.$brand_name.'/*{en,v980}*.jar',GLOB_BRACE) as $filename){
    echo $filename."</br>";
} 

This returned all the files that had either en, v980 or both. I just need to figure out if there is a way to say must contain both.


Solution

  • PHP's glob() essentially uses the same wildcarding/matching engine as a unix shell. With your version, you're searching for files that contain en,v980, and it's not being treated as "alternation". http://www.tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm

    Try

    glob('..../*{en,v980}*.jar')
    

    instead (note the {})