2013-02-26 26 views
1

如何捕捉和文件服務器上的文件名PHP正則表達式的文件名和數量

輸入:

news.jpg 
news_1.png 
asnews_2.gif 
asnews_3.jpeg 
aw_news_4.jpg 
aw_news.gif 

Outout:

Array 
(
[0] => Array 
    (
     [0] => news 
     [1] => news_1 
     [2] => asnews_2 
     [3] => asnews_3 
     [4] => aw_news_4 
     [5] => aw_news 
    ) 

[1] => Array 
    (
     [0] => 
     [1] => 1 
     [2] => 2 
     [3] => 3 
     [4] => 4 
     [5] => 
    ) 

[2] => Array 
    (
     [0] => news 
     [1] => news 
     [2] => asnews 
     [3] => asnews 
     [4] => aw_news 
     [5] => aw_news 
    ) 

) 

我在PHP嘗試使用preg_match_allpreg_replace_ca llback,我不知道如何正確使用。

preg_match_all('/(?: _???_ (?:_([\d]+))?$/im', $fullname, $result); // $fullname - string 

這是一個類似的例子 - /(?:(?:_([\d]+))?(.[^.]+))$/。你可以改變這一點。

回答

2
$result = array (array(), array(), array()); 

$dir = opendir ("/tmp"); 
while (($file = readdir ($dir)) !== false) 
{ 
    if ($file == '.' || $file == '..') continue; 

    $matches = array(); 
    preg_match ('/^(([^.]*?)(?:_([0-9]*))?)(?:\.|$)/', $file, $matches); 

    $result [0][] = $matches [1]; 
    $result [1][] = $matches [3]; 
    $result [2][] = $matches [2]; 
} 
closedir ($dir); 

print_r ($result); 

輸出是:

Array 
(
    [0] => Array 
    (
     [0] => news 
     [1] => news_1 
     [2] => asnews_2 
     [3] => asnews_3 
     [4] => aw_news_4 
     [5] => aw_news 
    ) 

    [1] => Array 
    (
     [0] => 
     [1] => 1 
     [2] => 2 
     [3] => 3 
     [4] => 4 
     [5] => 
    ) 

    [2] => Array 
    (
     [0] => news 
     [1] => news 
     [2] => asnews 
     [3] => asnews 
     [4] => aw_news 
     [5] => aw_news 
    ) 
) 
+0

幾乎得到它。但是很少有錯誤的結論,例如aw_news_4.jpg。查看問題(已編輯)。謝謝。 – 2013-02-26 10:01:37

+0

@Areku_UA查看更新後的答案。 – 2013-02-26 10:22:32

+0

一切都變好了。但再次失敗 - preg_replace_callback。看到我的第二個問題 - http://stackoverflow.com/questions/15087406/php-regexp-on-filename-and-number-preg-replace-callback。你可以寫出答案。非常感謝你,等待答案。 – 2013-02-26 11:04:18

0

嘗試explode函數在php.Explode中的字符串包含文件名。使用'。'作爲爆炸分析和extraxt分解數組來獲取文件名。

有關參考爆炸手動試試這個

http://php.net/manual/en/function.explode.php

+0

如果文件名有(點)明確,這將打破文件名。 – Garfield 2013-02-26 09:56:47

+0

無所謂..以'。'最後一次出現。並拆分字符串 – 2013-02-26 10:11:27