PHP Regex 获取 youtube 视频 ID? [英] PHP Regex to get youtube video ID?

查看:43
本文介绍了PHP Regex 获取 youtube 视频 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何从 url 中获取 youtube id,而不管 URL 中有哪些其他 GET 变量.

例如使用此视频:http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=related
所以在 v= 和下一个 &

之前

解决方案

使用 parse_url()parse_str().>

(您几乎可以将正则表达式用于任何事情,但它们很容易出错,因此如果有专门针对您要完成的任务的 PHP 函数,请使用它们.)

parse_url 接受一个字符串并将其切割成一个包含一堆信息的数组.您可以使用此数组,也可以指定您想要的一项作为第二个参数.在本例中,我们对查询感兴趣,即 PHP_URL_QUERY.

现在我们有了查询,它是 v=C4kxS1ksqtw&feature=relate,但我们只想要 v= 之后的部分.为此,我们转向 parse_str ,它基本上类似于字符串上的 GET .它接受一个字符串并创建字符串中指定的变量.在这种情况下,创建了 $v$feature.我们只对 $v 感兴趣.

为了安全起见,您不想只将 parse_url 中的所有变量存储在您的命名空间中(请参阅 mellowsoon 的评论).而是将变量存储为数组的元素,以便您可以控制要存储的变量,并且不会意外覆盖现有变量.

把所有东西放在一起,我们有:

工作示例

<小时>

呵呵 - 谢谢查尔斯.这让我发笑,我以前从未见过 Zawinski 的话:

有些人在遇到问题时会想‘我知道,我会使用正则表达式.’现在他们有两个问题.杰米·扎温斯基

Can someone show me how to get the youtube id out of a url regardless of what other GET variables are in the URL.

Use this video for example: http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=related
So between v= and before the next &

解决方案

Use parse_url() and parse_str().

(You can use regexes for just about anything, but they are very easy to make an error in, so if there are PHP functions specifically for what you are trying to accomplish, use those.)

parse_url takes a string and cuts it up into an array that has a bunch of info. You can work with this array, or you can specify the one item you want as a second argument. In this case we're interested in the query, which is PHP_URL_QUERY.

Now we have the query, which is v=C4kxS1ksqtw&feature=relate, but we only want the part after v=. For this we turn to parse_str which basically works like GET on a string. It takes a string and creates the variables specified in the string. In this case $v and $feature is created. We're only interested in $v.

To be safe, you don't want to just store all the variables from the parse_url in your namespace (see mellowsoon's comment). Instead store the variables as elements of an array, so that you have control over what variables you are storing, and you cannot accidentally overwrite an existing variable.

Putting everything together, we have:

<?php
$url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
echo $my_array_of_vars['v'];    
  // Output: C4kxS1ksqtw
?> 

Working example


Edit:

hehe - thanks Charles. That made me laugh, I've never seen the Zawinski quote before:

Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.Jamie Zawinski

这篇关于PHP Regex 获取 youtube 视频 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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