簡體   English   中英

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

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

考慮以下文件結構:

/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

我需要檢索名稱包含目錄中最高數值的文件。 在上面的示例中,它是locaux-S05_1.html

我想出了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?

}

任何指針將不勝感激。

嘗試這個:

$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

我對排序方法不滿意,也許有人可以以此為基礎,因為您不能將浮點數用作數組鍵(它們被轉換為整數,這是不好的。)我還假設您希望先按下划線前的數字對它們進行排序,然后再將第二個數字用作次級標准。

我找到了一種更簡單的方法:

$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