【问题标题】:Check filename inside a folder contains a pattern using glob()使用 glob() 检查文件夹内的文件名是否包含模式
【发布时间】:2015-09-14 23:17:13
【问题描述】:

我需要检查文件夹内的文件是否包含'_' 符号。我使用 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
 {

 }

我需要获取文件名中包含“_”的文件。我试过了

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

但它不起作用

【问题讨论】:

    标签: php file glob dir


    【解决方案1】:

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

    // 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
    

    【讨论】:

    • 我用过 $report_files = glob("\/user_uploads\/reportcards\/term_10'.'/*'.'_*\.pdf'"); //这对我有用。谢谢你给我这个主意。
    【解决方案2】:

    首先你忘记了术语后面的引号。

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

    其次,user_uploads 后面有两个斜杠。

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

    【讨论】:

    • 我忘记在问题中为术语添加引号。
    • 我需要过滤包含下划线的文件名。
    猜你喜欢
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 2020-06-17
    • 2014-05-10
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多