php - scandir 并返回匹配的文件

我正在尝试使用 scandir()foreach() 获取匹配的文件数组。

当我运行 scandir() 时,它会返回所有文件列表。这里没问题。

现在在第二步中,当我执行 foreach scandir()s 数组时,我只得到一个匹配的文件。但是有两个文件调用(请注意,在执行 foreach 之前,我的 scandir() 会返回包括这两个文件在内的所有文件);

widget_lc_todo.php
widget_lc_notes.php

我的代码中缺少某些东西,我不知道是什么:-(

这是我的代码:

$path = get_template_directory().'/templates';
$files = scandir($path);
print_r($files);
$template = array();
foreach ($files as $file){      
    if(preg_match('/widget_lc?/', $file)):
         $template[] = $file;
         return $template;

    endif;
}
print_r($template);

最佳答案

上面的代码会在找到第一个匹配文件后立即调用 return,这意味着 foreach 循环会在 preg_match 返回 true 时立即退出。在 foreach 循环退出之前,您不应该返回:

// ...
foreach ($files as $file){      
    if(preg_match('/widget_lc?/', $file)) {
         $template[] = $file;
    }
}
return $template;
// ...

https://stackoverflow.com/questions/16591736/

相关文章:

avr - 使用USBASP编程器进行SPI通信

python - 制作包含负值的对数标度彩色图

windows-installer - MSI 中的 "installation script"是什

c# - 页脚按钮的 Gridview colspan

amazon-s3 - S3 如何在上传时分配时间戳?

erlang - 如何使用 PEM key 文件在 Erlang 中通过 SSH 连接

c - 在 C 中实现 hmac sha1

apache - 将模块加载到 Apache

perl - utf8 "\xFF"未映射到 tokenizer.perl 第 44 行

Django - Python help_text 作为可点击的图标