finding files in a dir

≯℡__Kan透↙ 提交于 2019-12-19 03:59:10

问题


I have a directory with a lot of files inside:

pic_1_79879879879879879.jpg
pic_1_89798798789798789.jpg
pic_1_45646545646545646.jpg
pic_2_12345678213145646.jpg
pic_3_78974565646465645.jpg
etc...

I need to list only the pic_1_ files. Any idea how I can do? Thanks in advance.


回答1:


The opend dir function will help you

$dir ="your path here";

$filetoread ="pic_1_";
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
               if (strpos($file,$filetoread) !== false)
                echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
            }
            closedir($dh);
        }
    }

good luck see php.net opendir




回答2:


Use the glob() function

foreach (glob("directory/pic_1_*") as $filename) {
  echo "$filename";
}

Just change directory in the glob call to the proper path.

This does it all in one shot versus grabbing the list of files and then filtering them.




回答3:


This is what glob() is for:

glob — Find pathnames matching a pattern

Example:

foreach (glob("pic_1*.jpg") as $file)
{
    echo $file;
}



回答4:


Use scandir to list all the files in a directory and then use preg_grep to get the list of files which match the pattern you are looking for.




回答5:


This is one of the samples from the manual

http://nz.php.net/manual/en/function.readdir.php

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

you can modify that code to test the filename to see if it starts with pic_1_ using something like this

if (substr($file, 0, 6) == 'pic_1_')

Manual reference for substr

http://nz.php.net/manual/en/function.substr.php



来源:https://stackoverflow.com/questions/5959545/finding-files-in-a-dir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!