Wednesday, July 3, 2024
HomeLanguagesPhpHow to get YouTube video ID with PHP Regex ?

How to get YouTube video ID with PHP Regex ?

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 url’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

 

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments