简体   繁体   English

php查找文件名中值最高的文件

[英]php find file with highest value in its filename

Consider this file structure: 考虑以下文件结构:

/folder/locaux-S04_3.html
/folder/blurb.txt
/folder/locaux-S04_2.html
/folder/locaux-S05_1.html
/folder/tarata.02.jpg
/folder/locaux-S04_1.html
/folder/dfdsf.pdf

I need to retrieve the file which name contains the highest numeric value in a directory. 我需要检索名称包含目录中最高数值的文件。 In the above example, it is locaux-S05_1.html 在上面的示例中,它是locaux-S05_1.html

I came up with glob() as an efficient way to only get the locaux-S*.html files but i'm stuck in the next step: finding the one which filename contains the highest value. 我想出了glob()作为仅获取locaux-S * .html文件的有效方法,但我陷入了下一步:找到文件名包含最高值的文件。

$files= glob(LOCAUX_FILE_PATH.'/locaux-S*.html');

foreach($files as $key=> $value){
    // loop through and get the value in the filename. Highest wins a trip to download land!

$end = strrpos($value,'.');
$len= strlen($value);
$length = $len-$end;
$str = substr($value,8,$length);
// this gives me the meat, ex: 03_02. What next?

}

Any pointer would be very appreciated. 任何指针将不胜感激。

Try this: 尝试这个:

$files = glob(LOCAUX_FILE_PATH.'/locaux-S*.html');
$to_sort = array();

foreach ($files as $filename)
{
    if (preg_match('/locaux-S(\d+)_(\d+)\.html/', $filename, $matches)) {
        $to_sort[$matches[1].'.'.$matches[2]] = $filename;
    }
}

krsort($to_sort);
echo reset($to_sort); // Full filepath of locaux-S05_1.html in your example

I'm not happy with the sorting method, perhaps someone could build on this, as you can't use floats as array keys (they're converted to integers, which is no good.) I've also made the assumption that you want them to be sorted by the number before the underscore first, then to use the second number as the secondary order criterion. 我对排序方法不满意,也许有人可以以此为基础,因为您不能将浮点数用作数组键(它们被转换为整数,这是不好的。)我还假设您希望先按下划线前的数字对它们进行排序,然后再将第二个数字用作次级标准。

I found a simpler way: 我找到了一种更简单的方法:

$files= glob(LOCAUX_FILE_PATH.'/locaux-S*.html');
sort($files); // sort the files from lowest to highest, alphabetically
$file  = array_pop($files); // return the last element of the array

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

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