使用 glob() 检查文件夹内的文件名是否包含模式

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

我需要检查文件夹中的文件是否包含 '_' 符号。我使用 glob 函数从服务器位置获取文件。但我不知道要检查文件名是否包含文件名中任何位置的符号。 我有具有如下格式名称的文件。 student_178_grade1A

我曾经这样做过

$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
 {

 }

我需要获取 filename.I 中包含“_”的文件

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

但它不起作用

首先,您忘记了术语后的引号。

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

其次你在 user_uploads 之后有两个斜线。

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

您的正则表达式似乎不正确。这可能会做你想要的:

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

如果您不完全理解正则表达式的作用,我在下面做了一个快速总结。还有一个很棒的网站可以试用正则表达式,并提供有关如何构建正则表达式的文档 here

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