我正在尝试使用 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;
// ...
关于php - scandir 并返回匹配的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16591736/