在名称中包含子字符串的目录中获取文件名数组

Getting array of filenames in a directory which contains substring in their name

我有一个包含一些文件名的目录。我想获取该目录中包含子字符串的所有文件。

MyDir =>
    - Hello12.pdf
    - ABC.pdf
    - hello.pdf
    - JohnDoe.pdf
    - hello33.pdf

我想给 'Hello' 并获取所有包含 Hello 及其扩展名的文件名;并得到像 ['Hello12.pdf', 'hello.pdf, 'hello33.pdf']

这样的结果
$dir = public_path('files/MyDir');

如何在 MyDir 目录中的文件名中包含 'Hello' 子字符串的数组中获取文件?


从这条路走是个好方法吗?

foreach(glob($dir . '/*.pdf') as $filename){
     var_dump($filename);
}

您可以使用scandir方法获取所有文件名。然后遍历它并找到匹配项

$dir = public_path('files/MyDir');
$files =  scandir ($dir);
$match = "Hello";
$match_files = array();
foreach ($files as $file) {
  if((stripos($file, $match) !== false)
    $match_files[]=$file;
}
print_r($match_files);

首先你需要扫描目录然后找到字符串并将它们添加到数组

<?php
$i = scandir(__DIR__ . '/files/MyDir', 1);
$array = [];
foreach ($i as $x) {
    if (strpos($x, 'hello') !== FALSE) {
        $array[] = $x;
    }
}
echo var_export($array, true);