2011-05-24 30 views
1

由於腳本中的限制,我遇到了一個問題,我需要確保一個字符串匹配兩個正則表達式模式中的一個,而只調用一次preg_match()在一個preg_match中匹配兩個正則表達式

下面是我的一些代碼:

public static function get_file_host_from_link($link) 
{ 
    foreach(Filehosts::$file_hosts as $key => $val) 
    { 
     if(preg_match("#{$val["regex"]}#", $link)) 
     { 
      // We have a match, return this file host information 
      return $key; 
     } 
    } 
    // We've looped through all the file hosts and it hasn't matched, 
    // return false 
    return false; 
} 

現在,隨着配套Fileserve.com URL的是,可以有兩種有效的URL結構的問題。其中之一是:

http://www.fileserve.com/file/aHd8AHD 

另:

http://www.fileserve.com/file/zR8VJVM/file_name.zip 

此刻,我可以用這個正則表達式匹配第一個結構完美的罰款:^http://www.fileserve.com/file/[a-zA-Z0-9]+$但我也需要搭配其他URL結構使用這樣的東西:http://www.fileserve.com/[a-zA-Z0-9]+/[a-zA-Z0-9_-\.]+$。我如何使用現有的代碼執行此操作,僅調用preg_match()一次?我想過這樣的事情:

(^http://www.fileserve.com/file/[a-zA-Z0-9]+$|http://www.fileserve.com/[a-zA-Z0-9]+/[a-zA-Z0-9_-\.]+$)

這在我的知識是指「匹配第一個正則表達式或第二個」,但我不知道這是否會工作。

謝謝!

+0

你試過了嗎? – 2011-05-24 19:43:42

回答

6

下面應該工作:

^http://www.fileserve.com/file/[a-zA-Z0-9]+(/[-a-zA-Z0-9_\.]+)?$ 

一切後,?括號使其可選。

另請注意,字符類別[a-zA-Z0-9_-\.]無效,因爲-指定範圍,除非它在轉義或開始時指定。

你要麼[-a-zA-Z0-9_\.][a-zA-Z0-9_\-\.](我用我的第一個答案)。

+0

這工作。比我更快鍵入它... – Lucius 2011-05-24 19:45:28

+0

不敢相信我沒有想到使用可選組...謝謝! – Josh 2011-05-24 19:49:04

相關問題