[英]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);
首先,您需要掃描dir,然后找到字符串並將其添加到數組中
<?php
$i = scandir(__DIR__ . '/files/MyDir', 1);
$array = [];
foreach ($i as $x) {
if (strpos($x, 'hello') !== FALSE) {
$array[] = $x;
}
}
echo var_export($array, true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.