doutuzhuohao6449 2015-06-22 07:14
浏览 39
已采纳

如何在文件夹中按名称搜索图像?

I have a MySQL table with a column "rounds" and each "rounds" has his own photos. Exemple round1 has photos from start=380 end=385. This means it has 6 photos and the name of the photos contains 380,381,382,383,384 or 385 inside.

I use this PHP code to display the photos from the whole folder:

$dirname = "photos";
$images = scandir($dirname);
sort($images,SORT_NUMERIC);
krsort($images);
$ignore = Array(".", "..");

foreach($images as $curimg){
    if(!in_array($curimg, $ignore)) {

        echo "<p align=\"center\">Photo $curimg</p>";
        echo "<img class=\"img-responsive\" src=\"". $dirname . '/' . $curimg ."\">";
    }
}

I need some help to adjust my code for it search only photos from the folder that contains inside their name 380,381,382,383,384 or 385.

I think the code below could do it but I don't know how to adjust it with the first code.

$start=380;
$end=385;

for($i=$start; $i<=$end; $i++) {
echo "$i<br>";
}
  • 写回答

2条回答 默认 最新

  • dqba94394 2015-06-22 07:33
    关注

    This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex.

    According to the top comment on the docs page, what you could do is something like this:

    <?php
        $dirname = "photos";
        $filenames = glob("$dirname/*{380,381,382,383,384,385}*", GLOB_BRACE);
    
        foreach ($filenames as $filename)
        {
            echo $filename . "<br />";
        }
    ?>
    

    The GLOB_BRACE options lets you specify a list of values in braces, and the asterisks around them allow those numbers to appear anywhere in the file name. You can then iterate over the returned array and do whatever you want with $filename.

    You could use your example for loop to automatically build a string to pass to glob.

    Here's the output when I ran this on a test directory I made:

    photos/380.zip
    photos/asdf382ghj.txt
    photos/385.bmp
    

    Note that another file I put in there, a386b.xlsx, didn't match the pattern and doesn't appear on the list.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义