2010-10-06 43 views
0

考慮這個文件結構:PHP查找文件

/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? 

} 

任何指針將不勝感激。

回答

2

試試這個:

$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 

我不開心的排序方法,也許有人可以擴大戰果,因爲你不能使用浮點數作爲數組鍵(他們轉換爲整數,這是不行的)。我還假設你希望它們先按下劃線之前的數字排序,然後再用第二個數字作爲次級標準。

+0

假設是正確的,代碼有趣的一點! – pixeline 2010-10-06 22:34:58

1

我發現了一個簡單的方法:

$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