开发者

PHP: Extract video ID from YouTube URLs

Do I do something wrong? I need the youtube code, but it doesn't return the real value.

if(preg_match_all("http:\/\/www\.youtube\.com\/v\/(.*)(.*)", $row->n_texto, $matches){
    $code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$matches[1][0]."/0.jpg";
}

Edit - ircmaxell Based on the comment,开发者_运维问答 the link structure in the text is:

http:// www.youtube.com/v/plMvAh10HVg%26hl=en%26fs=1%26rel=0


Update

The problem is: my code return a link like this:

http://www.youtube.com/v/plMvAh10HVg%26hl=en%26fs=1%26rel=0

Can I stop it with regexp before appear %26hl=en%26fs=1%26rel=0?


Your regex is not correct. There are more than a few things wrong with it. Now, as far as what you want, try this:

#http://(?:.*)youtube.com/v/([^/\#?]+)#

Now, as for why, let's look at the regex:

http://(?:.*)youtube.com

You're looking for a string that starts with http://, has anything after (www., ww2., or nothing).

/v/

You're looking for /v/ as the start of the URL.

([^/\\#?]+)

You're looking for everything else UP TO another /, a query string (?) or a anchor (#). So that should match the ID you're looking for.

So, it would be

if(preg_match("#http://(?:.*)youtube.com/v/([^/\#?]+)#", $row->n_texto, $matches){
    $code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$matches[1]."/0.jpg";
}

If you wanted to find all:

if(preg_match_all("#http://(?:.*)youtube.com/v/([^/\#?]+)#", $row->n_texto, $matches){
    foreach ($matches[1] as $match) {
        $code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$match."/0.jpg";
    }
} 


the link provided has a space before the 1st w in www.youtube.com, the code you need is :

if(preg_match_all("%http://www\.youtube\.com/v/([\w]+)%i", $row->n_texto , $matches)){
    $code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$matches[1][0]."/0.jpg";
}

also, the url you have is encoded, you may want to use urldecode($row->n_texto) before using it.


^http://\w{0,3}.?youtube+\.\w{2,3}/watch\?v=[\w-]{11}

according to http://www.regexlib.com/REDetails.aspx?regexp_id=2569

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜