我想获得所有列表文件夹和子文件夹,只有文件名和文件名 示例输出:
folder name:
source/1
source/1/2
source/1/2/3
filename
0.jpg
1.jpg
3.jpg
这是我的代码,此代码工作正常,但此代码显示文件名为..
$rootpath = 'source';
$fileinfos = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootpath)
);
foreach($fileinfos as $pathname => $fileinfo) {
if (!$fileinfo->isFile()) continue;
echo($pathname).'<br>';
}
修改 如何使用正则表达式或preg-match FOLDERNAME /子文件夹/ filename.jpg
如何仅获取foldername/subfolder/
且仅filename.jpg
$filepath = 'foldername/subfolder/filename.jpg';
$folder= (preg_match('~[^A-Za-z0-9_\./\]~', $filepath));
echo 'folder:' .'<br>' .$folder;
$filename =(preg_match('....', $filepath));
echo 'fileneme' .'<br>' .$filename;
输出
folder:
foldername/subfolder/
filename:
filename.jpg
感谢
答案 0 :(得分:0)
下面的代码段可能有所帮助。如果您决定只获得
FILES
;只需传递String&#39;文件&#39;作为函数scanDirRecursive
的第3个参数。默认情况下,该函数返回给定目录中所有DIRECTORIES
和SUB-DIRECTORIES
的列表:$directory
(第一个参数)。然而;你可能仍然得到DIRECTORIES
&amp;FILES
一气呵成。
要做到这一点;只需传递字符串:both
作为第3个论点....
希望这对你有所帮助。
CHEERS&amp;好运!!! 强>
<?php
$rootPath = 'source';
$regex = null;
/**
* @param string $directory => DIRECTORY TO SCAN
* @param string $regex => REGULAR EXPRESSION TO BE USED IN MATCHING FILE-NAMES
* @param string $get => WHAT DO YOU WANT TO GET? 'dir'= DIRECTORIES, 'file'= FILES, 'both'=BOTH FILES+DIRECTORIES
* @param bool $useFullPath => DO YOU WISH TO RETURN THE FULL PATH TO THE FOLDER OR JUST ITS NAME?
* @param array $dirs => LEAVE AS IS: USED DURING RECURSIVE TRIPS
* @return array
*/
function scanDirRecursive($directory, $regex=null, $get="dir", $useFullPath=false, &$dirs=[], &$files=[]) {
$iterator = new DirectoryIterator ($directory);
foreach($iterator as $info) {
$fileDirName = $info->getFilename();
if ($info->isFile () && !preg_match("#^\..*?#", $fileDirName)) {
if($get == 'file' || $get == 'both'){
if($regex) {
if(preg_match($regex, $fileDirName)) {
if ($useFullPath) {
$files[] = $directory . DIRECTORY_SEPARATOR . $fileDirName;
}
else {
$files[] = $fileDirName;
}
}
}else{
if($useFullPath){
$files[] = $directory . DIRECTORY_SEPARATOR . $fileDirName;
}else{
$files[] = $fileDirName;
}
}
}
}else if ($info->isDir() && !$info->isDot()) {
$fullPathName = $directory . DIRECTORY_SEPARATOR . $fileDirName;
if($get == 'dir' || $get == 'both') {
$dirs[] = ($useFullPath) ? $fullPathName : $fileDirName;
}
scanDirRecursive($fullPathName, $regex, $get, $useFullPath, $dirs, $files);
}
}
if($get == 'dir') {
return $dirs;
}else if($get == 'file'){
return $files;
}
return ['dirs' => $dirs, 'files' => $files];
}
// GET ONLY DIRECTORIES IN THE 'source' FOLDER + SUB-FOLDERS
$directories = scanDirRecursive($rootPath, $regex, 'dir', false);
// GET ONLY FILES IN THE 'source' FOLDER + SUB-FOLDERS
$files = scanDirRecursive($rootPath, $regex, 'file', false);
// GET BOTH FILES & DIRECTORIES IN THE 'source' FOLDER + SUB-FOLDERS
$both = scanDirRecursive($rootPath, $regex, 'both', false);
var_dump($directories);
var_dump($files);
var_dump($both);