How can I write a function to check whether the provided URLs is youtube or vimeo?
For instance, I have this two URLs that I store in a database as strings,
http://vimeo.com/24456787
http://www.youtube.com/watch?v=rj18UQjPpGA&feature=player_embedded
If the URL is youtube then I will rewrite the URL to,
http://www.youtube.com/embed/rj18UQjPpGA?rel=0&wmode=transparent
If the URL is vimeo then I will rewrite this URL to,
http://vimeo.com/moogaloop.swf?clip_id=24456787
Thanks.
As others have noted in the comments, this is a quick and dirty solution that does not handle edge cases well. If the url contains "youtube"(example.com/youtube) it will return a false positive. The
parse_url()
solution mentioned below is a much more robust solution.Regular expressions work well for this type of thing, but often
strpos
orsubstr
are faster performance wise. Check out the PHP documentation forpreg_match()
. Below the examples there is a note for exactly this thing.Here is prototype code:
Obviously returning a string isn't the best idea, but you get the point. Substitute your own business logic.
You can use
preg_match()
:Since all you want to do is check for the presence of a string, use stripos. If it doesn't have youtube.com or vimeo.com in it, the url is malformed, right? stripos is case insensitive, too.
Surprising no one has mentioned that youtube urls can also contain the domain 'youtu.be' in which case all of the above solutions would have to be adapted to cater for that eventuality.
Use the
parse_url
function to split the URL up and then just do your normal checksWill give you this array
You can try my solution:
Use: