chris mccoy
chris mccoy

Reputation: 347

youtube link regex

im trying to make this work for all youtube links, which is working, except for youtube.com/v/videoid

only watch?v= is working with this regex, any assistance is greatful.

/http:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*/i

Upvotes: 2

Views: 3749

Answers (4)

Muhammad Tahir
Muhammad Tahir

Reputation: 2485

done use regular expression. This is better way to grab the video ID

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

working here

Upvotes: 0

Manuel E. Serrano
Manuel E. Serrano

Reputation: 31

this is my first contribution, hope it helps.

$url = "https://www.youtube-nocookie.com/embed/lCpaCAfhCH4";

if (preg_match("/^((https?:\/\/)?(w{0,3}\.)?youtu(\.be|(be|be-nocookie)\.\w{2,3}\/))((watch\?v=|v|embed)?[\/]?(?P<video>[a-zA-Z0-9-_]{11}))/si", $url, $matches)) {

echo $matches['video'];

}

This regex works with any youtube url format (long, short, embed, secure, etc)

Thanks!

Upvotes: 3

Oli
Oli

Reputation: 2464

/((http:\/\/)?(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/v\/)([\w-]{11}).*|http:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*)/i

Upvotes: 5

user432219
user432219

Reputation:

The website Regular Expression Library is a good source for that. Try the following link: http://www.regexlib.com/Search.aspx?k=youtube

Upvotes: 7

Related Questions