PHP Regex to get YouTube Video ID

PHPServer Side ProgrammingProgramming

The parse_url and parse_str functions can be used to get the ID of a specific YouTube video.

Example

 Live Demo

<?php
   $url = " https://www.youtube.com/watch?v=VX96I7PO8YU ";
   parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array );
   echo $my_array['v'];
?>

Output

VX96I7PO8YU

In the above code, the parse_url function takes in a string and slices it into an array of information. The element that the user specifically wants to work with can be specified as a second argument or the entire array can be used.

A YouTube video has an ID that can be seen in the URL. The goal is to fetch the ID after the letter ‘v’ and before ‘&’. To accomplish this, the parse_str function can be used. It is similar to GET functionality, which takes a string and creates variables that are specified by the string.

For example − If v=5R60Tpz3Bow, it creates a variable named $v. This is stored as an array element, thereby giving control over the variable being stored, so as to not overwrite it accidentally.

Note − Regular expression, also known as regex can be used to tackle many problems, but are prone to errors. Hence, they need to be used with care.

raja
Published on 30-Dec-2019 06:41:00
Advertisements