简体   繁体   中英

RecursiveIterator return array with file extension

I'm using this function to find all pictures in a folder and sub-folder:

function rsearch($folder, $pattern) {
    $dir = new RecursiveDirectoryIterator($folder);
    $ite = new RecursiveIteratorIterator($dir);
    $files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
    $fileList = array();
    foreach($files as $file) {
        $fileList = array_merge($fileList, $file);
    }
    return $fileList;
}
$list_of_file=rsearch($data_directory,'/^.+\.(jpg|jpeg|png|gif|tiff)$/i');
echo 'longueur '.count($list_of_file);
print_r($list_of_file);

And here the result :

    Array
(
    [0] => file-user/rep/username/images\asura.jpg
    [1] => jpg
    [2] => file-user/rep/username/images\beyourself.jpg
    [3] => jpg
    [4] => file-user/rep/username/images\subfolder\logo3.png
    [5] => png
    [6] => file-user/rep/username/images\gmail.gif
    [7] => gif
)

1) How can I change the \\ before filename to a /

2) Why the array return the extension just after the file itself ? how to prevent it?

Try to var_dump $files and you will see. If you dont want to put both elements of the $file array into your $fileList then dont use the array_merge simply do:

   foreach($files as $file) {
       $fileList[] = $file[0];
   }

And for pretty rough and ready fix to the \\ do a str_replace or similar. Something like:

   foreach($files as $file) {
       $fileList[] = str_replace('/','\\',$file[0]);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM