1

i want one php regex to extract the id (VmzI60RQG0fuw) from these

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

i tested this, but its not work on the 3 probability

preg_match('~(media\.giphy\.com/media/([^ /]+)/giphy\.gif|i.giphy.com/([^ /]+).gif)~i', $this->url, $matches) 
Mostafa Elkady
  • 5,285
  • 10
  • 42
  • 64

1 Answers1

2

Here is one that should work:

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

See the regex demo

The third alternative is giphy\.com/gifs/(?:.*-)?([^ /]+):

  • giphy\.com/gifs/ - a subpath giphy.com/gifs/
  • (?:.*-)? - (optional group, the text may go missing due to (?:...)? construct) matches all characters up to the last - (perhaps, replacing with \S*- or [^\s/]*- can make it a bit more precise)
  • ([^ /]+) - matches and captures the ID (one or more characters other than a space and /).

Since it is for PHP, you can also use a branch reset ((?|...|...)) so that all the captured groups could have one and the same ID #1.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • Please note that `.*` can work if the URLs are analyzed independently. If they appear in some context, you would need to replace `.*` with `\S*`, or maybe even `[^\s>/]*` – Wiktor Stribiżew Mar 26 '16 at 22:56
  • Here it is: [`https?://(?|media\.giphy\.com/media/([^ /\n]+)/giphy\.gif|i\.giphy\.com/([^ /\n]+)\.gif|giphy\.com/gifs/(?:.*-)?([^ /\n]+))`](https://regex101.com/r/eC9gL6/3). Note that `\n` inside `[...]` is added since it is a multiline string demo, I do not think you need it in the real code. – Wiktor Stribiżew Mar 26 '16 at 23:03
  • this is great, i want to learn how to make a great regex code like that .. can you advice me how – Mostafa Elkady Mar 26 '16 at 23:08
  • I do not know your level of regex knowledge :) so that I can only suggest doing all lessons at [regexone.com](http://regexone.com/), reading through [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info) (with many other links to great online resources), and the community SO post called [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). A [rexegg.com](http://rexegg.com) is also a great site. – Wiktor Stribiżew Mar 26 '16 at 23:13