2011-04-07 55 views
0

我有一個函數,它從一個文件夾中獲取文件的名稱,按日期對它們進行排序,然後創建一個指向該文件的鏈接。但是,這隻適用於實際文件名在單詞之間有空格的情況。如果我將連字符添加到文件名中,則按日期排序無法正常工作。正確的preg_match代碼按日期排序文件名?

的工作有相應的文件名:

介紹一月2011.pdf

演示八月2010.pdf

表現可能2010.pdf

如果我加連字符命令中斷的文件名稱:

介紹,一月2011.pdf

演示八月-2010.pdf

介紹五月-2010.pdf

我如何可以改變的preg_match(),因此,它需要考慮連字符?這裏是我的代碼:

$linkdir="documents/presentations"; 
$dir=opendir("documents/presentations"); 
$files=array(); 

while (($file=readdir($dir)) !== false) 
{ 
    if ($file != "." and $file != ".." and $file != "index.php") 
    { 
    array_push($files, $file); 
    } 
} 

closedir($dir); 

function date_sort_desc($a, $b) 
{ 
    preg_match('/\w+ \d{4}/', $a, $matches_a); 
    preg_match('/\w+ \d{4}/', $b, $matches_b); 
    $timestamp_a = strtotime($matches_a[0]); 
    $timestamp_b = strtotime($matches_b[0]); 
    if ($timestamp_a == $timestamp_b) return 0; 
    return $timestamp_a < $timestamp_b; 
} 

usort($files, 'date_sort_desc'); 

foreach ($files as $file){ 
    $name = substr($file, 0, strrpos($file, '.')); 
    $filename = str_replace(" ", "%20", $file); 
    $name = str_replace("-", " ", $file); 
    print "<li><a href='/$linkdir/$filename' rel='external'>$name</a></li>"; 
} 

任何幫助將非常感激。

回答

1

'/ \ w + \ d {4} /'查找單詞,空白和四位數; '/ \ w + [ - ] \ d {4} /'應該在單詞和數字之間尋找空格或連字符。

+0

超級巨星 - 非常感謝你! – Jonathan 2011-04-07 09:02:47

2

以下兩行:

preg_match('/\w+ \d{4}/', $a, $matches_a); 
preg_match('/\w+ \d{4}/', $b, $matches_b); 

它們匹配的若干 '字狀的字符'(\ W),一個空格,然後四位數字(\ d)。

您可以更改正則表達式來接受空格或短劃線:'[ -]'或'(|-)',而不是空格''。這不應該破壞strtotime()函數調用。

如果是這樣,你可以通過添加改變date_sort_desc()頂部以下內容:

$a = str_replace("-", " ", $a); 
$b = str_replace("-", " ", $b); 

在這種情況下,你不會需要改變正則表達式。

+0

+1,因爲RikkusRukkus解決了strtotime()可能存在的問題。但補救措施應該在比賽前應用,或者模式也必須改變。 – 2011-04-07 09:15:03

0

然後當使用不同的字符時,會不斷更新您的代碼。爲什麼不使用/ \ w + \ W?\ d {4} /來捕獲可能顯示的任何非字母數字字符?

+0

Markdown幫助 - http://stackoverflow.com/editing-help#syntax-highlighting – 2012-10-26 04:35:45