Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to get YouTube video ID with PHP Regex ?

  • 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 ‘youtu.be/’ . 
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 youtu.be/. So as the query starts from ‘?’ or ‘yout.be/’, start regex by ‘?’ or look for ‘yout.be/’. It will ignore the URL part before ‘?’ or ‘yout.be/’. 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\/|youtu.be\/)[a-zA-Z0-9_-]{11}#", $url, $match);

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

php




<?php
$url = 'https://youtu.be/hjGD08xfg9c
Output: 
Array
(
    [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. 
Example: 
 

php




<?php
 
// 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'];
 
?>
Output: 
hjGD08xfg9c
hjGD08xfg9c

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!