PHP:如何检查 URL 是 Youtube 还是 vimeo
如何编写一个函数来检查提供的 URL 是 youtube 还是 vimeo?
例如,我将这两个 URL 作为字符串存储在数据库中,
http://vimeo.com/24456787
http://www.youtube.com/watch?v=rj18UQjPpGA&feature=player_embedded
如果 URL 是 youtube,那么我将重写该 URL,
http://www.youtube.com/embed/rj18UQjPpGA?rel=0&wmode=transparent
如果 URL 是 vimeo,那么我将将此 URL 重写为,
http://vimeo.com/moogaloop.swf?clip_id=24456787
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用
parse_url
函数拆分 URL,然后执行正常检查就会给你这个数组
Use the
parse_url
function to split the URL up and then just do your normal checksWill give you this array
我最近编写了这个函数来完成此任务,希望它对某人有用:
I recently wrote this function to do exactly this, hopefully it's useful to someone:
正如其他人在评论中指出的那样,这是一个快速而肮脏的解决方案,不能很好地处理边缘情况。如果网址包含“youtube”(example.com/youtube),它将返回误报。下面提到的
parse_url()
解决方案是一个更强大的解决方案。正则表达式对于此类事情效果很好,但通常
strpos
或substr
性能更快。查看 PHP 文档preg_match()
。在示例下面有一个专门针对此问题的注释。这是原型代码:
显然返回字符串不是最好的主意,但你明白了。替换您自己的业务逻辑。
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.
您可以使用
preg_match()
:You can use
preg_match()
:由于您要做的只是检查字符串是否存在,因此请使用 stripos。如果其中没有 youtube.com 或 vimeo.com,则该网址格式错误,对吗? stripos 也不区分大小写。
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.
您可以尝试我的解决方案:
使用:
You can try my solution:
Use:
使用正则表达式。您使用什么语言?
编辑:注意到你的标签是 php。它会是这样的:
Use regular expressions. What language are you using?
Edit: noticed your tag was php. It would be something like this:
你可以试试这个
You can try this