2013-04-18 32 views
1

只是想知道如何提取或匹配特定的文件類型,因爲有很多畸形的URL和目錄。如何捕獲格式不正確的URL中的文件類型

所以我需要一個很好的正則表達式來匹配真正的正則表達式。

http://domain.com/1/image.jpg <-match .jpg 
http://domain.com/1/image_1.jpg/.gif <-match first .jpg 
http://domain.com/1/image_1.jpg/image.png <-match first .jpg 
http://domain.com/1/image_1.jpg <-match .jpg 
http://domain.com/1/image.jpg.jpeg <-match only the first .jpg 
http://domain.com/1/.jpg <-not match 
http://domain.com/.jpg.jpg <- not match 
/1/.jpg <-not match 
/.jpg.png <-match the first jpg 
/image.jpg.png <-match the first jpg 

我想用這段代碼:

preg_match_all('([a-zA-Z0-9.-_](jpg))i', $url, $matches); 

任何想法?

回答

0
preg_match('(^(http://domain.com/\w.*?\.jpg))i', $url, $matches); 

這將匹配從字符串開頭到第一個.jpg的所有內容。文件名部分必須以字母,數字或_開頭。

+0

這工作很好,但我忘了一些網址是不完整的,只是引用目錄像/1/.jpg.gif – greenbandit 2013-04-18 02:33:30

0

使用正則表達式解析URL通常是一個壞主意。有關相關問題,請參閱Getting parts of a URL (Regex)。特別是,看看this answer,然後意識到parse_url可能是一個好的開始。以$result['path']並使用文件名解析API來提取擴展名。

我不確定你到底在問什麼。

http://domain.com/1/image_1.jpg/.gif <-match first .jpg 
http://domain.com/1/image_1.jpg/image.png <-match first .jpg 

在這兩種情況下image_1.jpg是一個完全有效的目錄名。你可以在'/'上分割路徑並檢查每一個的「有效性」。

編輯我剛剛注意到你也需要這個來處理相對的URL。在這種情況下,parse_url不起作用。