简体   繁体   English

PHP-查找目录中与特定字符串匹配的所有所有文件并放入数组

[英]PHP - find all all files within directory that match certain string and put in array

I have a directory of images on a server that customers have uploaded. 我在客户上传的服务器上有一个图像目录。 I need to be able to get all files that match a certain string or item code and put them inside an array. 我需要能够获取与某个字符串或项目代码匹配的所有文件,并将它们放入数组中。 Filenames and extensions can always vary but each file will always have an 8 digit item code in the filename. 文件名和扩展名始终可以变化,但是每个文件的文件名中始终具有8位数字的项目代码。 So for instance say in my directory i have: 例如,在我的目录中,我有:

/images/

62115465.jpg
62115465-02.jpg
62115465-07.jpg
13452766.png
56773392.jpeg
56773392-avatar.jpg

I want to be able to pull out all the files that match the 8 digit item code so: 我希望能够提取出与8位项目代码匹配的所有文件,因此:

//all images that have 62115465 in the file name would give me

62115465.jpg
62115465-02.jpg
62115465-07.jpg

//or all images that have 56773392 in the file name would give me

56773392.jpeg
56773392-avatar.jpg

and then want them in an array like so: 然后将它们放在这样的数组中:

$all_files = array(
  '62115465.jpg',
  '62115465-02.jpg',
  '62115465-07.jpg'
);

I tried using the glob() function as below which can match some files like the 62115465.jpg but doesnt pick up the 2 other files with the -02 and -07 tags 我尝试使用下面的glob()函数,该函数可以匹配某些文件,例如62115465.jpg但没有使用-02-07标签拾取其他2个文件

$files = glob('62115465.'.*');
glob('62115465*');

note the removal of the . 注意删除. . glob() essentially replicates doing something like dir *.txt at a command prompt. glob()本质上是在命令提示符下复制执行dir *.txt的操作。

I know this question was answered already, but to the novice/intermediate coder, or anyone new to the glob() function ( AHEM ME COUGH ), it's pretty unclear what's going on here. 我知道这个问题已经回答了,但是对于新手/中级编码者,或者glob()函数新手AHEM ME COUGH )来说,目前还不清楚。 So, here's a full script that I cobbled together to do pretty much the same thing the OP asked for- search through a directory for all files beginning with the target prefix and add them to an array.: 因此,这是一个完整的脚本,我拼凑在一起以执行OP所要求的几乎相同的操作-在目录中搜索以目标前缀开头的所有文件,并将它们添加到数组中:

<?php
$imgs = array();
$dir =  $_SERVER['DOCUMENT_ROOT'].'/path/to/your/images';
$prefix = 'your-prefix_string-_-';
chdir($dir);
$matches = glob("$prefix*");
if(is_array($matches) && !empty($matches)){
    foreach($matches as $match){
        $imgs[] = $match;
    }
}
?>

你可以试试这个吗

 $files = glob('62115465.*');

Try like this- 尝试这样-

$files = glob("[^62115465]*.*);

Or like this: 或像这样:

$files = glob("62115465*.*);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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