如何在文件夹中按名称搜索图像? [英] How to search images by name inside a folder?

查看:218
本文介绍了如何在文件夹中按名称搜索图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有rounds列的MySQL表,每个rounds都有自己的照片。例子round1有来自start = 380 end = 385的照片。这意味着它有6张照片,照片名称中包含380,381,382,383,384或385。

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.

我使用此PHP代码显示整个文件夹中的照片:

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 ."\">";
    }
}

我需要一些帮助来调整我的搜索代码只有来自其名称380,381,382,383,384或385内的文件夹中的照片。

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>";
}


推荐答案

这看起来像是一份工作 glob ,它返回与指定模式匹配的文件名数组。我知道刚刚发布的另一个答案,但让我们提供一个替代正则表达式的方法。

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 />";
    }
?>

GLOB_BRACE 选项可让您指定一个清单大括号中的值,以及它们周围的星号允许这些数字出现在文件名中的任何位置。然后,您可以迭代返回的数组并使用 $ filename 执行任何操作。

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.

您可以使用您的示例 for 循环以自动构建一个字符串以传递给 glob

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

请注意我放入的另一个文件那里, a386b.xlsx ,与模式不匹配,没有出现在列表中。

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

这篇关于如何在文件夹中按名称搜索图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆