Skip to content
Related Articles

Related Articles

How to get YouTube video ID with PHP Regex ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 21 Oct, 2021

YouTube ID is a string of 11 characters, which consists of both upper and lower case alphabets and numeric values. It is used to define a YouTube video uniquely. A link to any YouTube video consists of its YouTube ID in a query format whose variable is generally written as ‘v’ or ‘vi’ or can be represented as ‘’ . 
Examples of YouTube ID from the link given below: 

In all these urls’s the string ‘hjGD08xfg9c’ is the YouTube ID. Now using this knowledge, a regular expression can be built for fetching the YouTube ID from a given link in PHP.
Regex: Now we know that there are five basic formats in which we can get a YouTube ID i.e. by v= or vi= or v/ or vi/ or So as the query starts from ‘?’ or ‘’, start regex by ‘?’ or look for ‘’. It will ignore the URL part before ‘?’ or ‘’. After that search for ‘v=’ or ‘vi=’ and store the next 11 characters and print it.
According to this logic the regex will be 

preg_match_all("#(?<=v=|v\/|vi=|vi\/|\/)[a-zA-Z0-9_-]{11}#", $url, $match);

Example: This example will show the YouTube ID in which input will be the link to YouTube. 


$url = '


    [0] => hjGD08xfg9c
    [1] => hjGD08xfg9c
    [2] => hjGD08xfg9c
    [3] => hjGD08xfg9c
    [4] => hjGD08xfg9c


Alternative: Instead of using regular expression we can access the variable or the query by using two functions that are parse_str() and parse_url(). The parse_str() takes parse_url() and an output variable as parameters and puts all the query values of the url in the output variable. The parse_url() takes the url in string format and an integer value and returns the list of different properties within the url depending on the value of integer passed. 


// Store the URL into variable
// Use parse_str() function to parse the query string
parse_str( parse_url( $url, PHP_URL_QUERY ), $youtube_id_v );
parse_str( parse_url( $url1, PHP_URL_QUERY ), $youtube_id_vi );
// Display the output
echo $youtube_id_v['v'] . "\n";
echo $youtube_id_vi['vi'];




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!