2016-03-26 27 views
1

的GIF ID我想一個PHP的正則表達式來從這些PHP的正則表達式得到giphy

http://i.giphy.com/VmzI60RQG0fuw.gif 
https://media.giphy.com/media/VmzI60RQG0fuw/giphy.gif 
http://giphy.com/gifs/VmzI60RQG0fuw 
http://giphy.com/gifs/music-videos-mariah-carey-dreamlover-VmzI60RQG0fuw 

我測試此提取ID(VmzI60RQG0fuw),但它不能在3概率工作

preg_match('~(media\.giphy\.com/media/([^ /]+)/giphy\.gif|i.giphy.com/([^ /]+).gif)~i', $this->url, $matches) 

回答

2

這裏是一個應該工作:

'~https?://(?|media\.giphy\.com/media/([^ /]+)/giphy\.gif|i\.giphy\.com/([^ /]+)\.gif|giphy\.com/gifs/(?:.*-)?([^ /]+))~i' 

regex demo

第三種方法是giphy\.com/gifs/(?:.*-)?([^ /]+)

  • giphy\.com/gifs/ - 子路徑giphy.com/gifs/
  • (?:.*-)? - (可選組,文本可能會丟失由於(?:...)?結構)直至最後-所有字符(匹配也許,替換爲\S*-[^\s/]*-可以使它更精確一點)
  • ([^ /]+) - 匹配並捕獲ID(一個或m個礦石字符以外的空格和/)。

由於它是針對PHP的,您還可以使用分支重置((?|...|...)),以便所有捕獲的組可以具有一個相同的ID#1。

+0

請注意,如果獨立分析URL,'。*'可以工作。如果它們在某些情況下出現,則需要用'\ S *'替換'。*',或者甚至可以用'[^ ​​\ s> /] *' –

+0

好,請添加這個http:// giphy。 com/gifs/VmzI60RQG0fuw –

+0

它是:['https?://(?| media \ .giphy \ .com/media /([^/\ n] +)/ giphy \ .gif | i \ .giphy \ .com /([^ /\n]+)\.gif|giphy\.com/gifs/(?:.*-)?([^/ \ n] +))'](https:// regex101。 COM/R/eC9gL6/3)。請注意''[']''裏面的'\ n'是由於它是一個多行字符串演示而添加的,我不認爲你需要它在真實的代碼中。 –