Search code examples
phpfileglobdir

Check filename inside a folder contains a pattern using glob()


I need to check the files inside a folder contains '_' symbol. I have used the glob function to get the files from server location. But I am unaware to check the filenames contains the symbol anywhere within the filename. I have files having names like the following format. student_178_grade1A

I have done like this.

$report_files=glob( '/user_uploads/'  . '/reportcards/' . 'term' . '_' . 10.'/*'.'.pdf' );

//this will return all files inside the folder.

if(count(report_files)>0)
 {
        //some stuff
 }
 else
 {

 }

I need to get the files which has '_' within the filename.I tried

glob( '/user_uploads/'  . '/reportcards/' . 'term' . '_' . 10.'/*[_]'.'.pdf' );

but its not working


Solution

  • Your regular expression doesn't seem correct. This might do what you want:

    // Find any file in the directory "/user_uploads/reportcards/term_10/" 
    // that has the file extension ".pdf"
    $report_files = glob("\/user_uploads\/reportcards\/term\_10\/(.*)\.pdf");
    
    // Find any file in the directory "/user_uploads/reportcards/term_10/" 
    // containing the character "_".
    $report_files = glob("\/user_uploads\/reportcards\/term\_10\/(.*)\_(.*)");
    
    // Find any file in the directory "/user_uploads/reportcards/term_10/" 
    // that has the file extension ".pdf" and contains the "_" character
    $report_files = glob("\/user_uploads\/reportcards\/term\_10\/(.*)\_(.*)\.pdf");
    

    If you don't understand exactly what the regular expression does, I made a quick summary of what is being done down below. There's also a great website to try out regular expresison with documentation on how to construct them here.

    \/ = escapes the / character
    \_ = escapes the _ character
    \. = escapes the . character
    (.*) = matches any character, number etc