PHP:如何检查 URL 是 Youtube 的还是 vimeo 的 [英] PHP: How to check whether the URL is Youtube's or vimeo's

查看:32
本文介绍了PHP:如何检查 URL 是 Youtube 的还是 vimeo 的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写函数来检查提供的 URL 是 youtube 还是 vimeo?

How can I write a function to check whether the provided URLs is youtube or vimeo?

例如,我将这两个 URL 作为字符串存储在数据库中,

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

如果 URL 是 youtube 那么我会将 URL 重写为,

If the URL is youtube then I will rewrite the URL to,

http://www.youtube.com/embed/rj18UQjPpGA?rel=0&wmode=transparent

如果 URL 是 vimeo 那么我将这个 URL 重写为,

If the URL is vimeo then I will rewrite this URL to,

http://vimeo.com/moogaloop.swf?clip_id=24456787

谢谢.

推荐答案

正如其他人在评论中指出的那样,这是一个快速而肮脏的解决方案,不能很好地处理边缘情况.如果 url 包含youtube"(example.com/youtube),它将返回误报.parse_url() 解决方案下面提到是一个更强大的解决方案.

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.

正则表达式适用于这种类型的事情,但通常strpossubstr 在性能方面更快.查看 preg_match() 的 PHP 文档.在示例下方有一个注释,说明了这件事.

Regular expressions work well for this type of thing, but often strpos or substr are faster performance wise. Check out the PHP documentation for preg_match(). Below the examples there is a note for exactly this thing.

这是原型代码:

function videoType($url) {
    if (strpos($url, 'youtube') > 0) {
        return 'youtube';
    } elseif (strpos($url, 'vimeo') > 0) {
        return 'vimeo';
    } else {
        return 'unknown';
    }
}

显然返回一个字符串不是最好的主意,但你明白了.替换您自己的业务逻辑.

Obviously returning a string isn't the best idea, but you get the point. Substitute your own business logic.

这篇关于PHP:如何检查 URL 是 Youtube 的还是 vimeo 的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆