9951 explained code solutions for 126 technologies

php-regexHow to use PHP regex to get a YouTube video ID?

Using PHP regex to get a YouTube video ID is a simple task. The following example code block will demonstrate how to do it:

$url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';

preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);

echo $match[1];

The output of the example code will be:


Code explanation

  1. $url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'; - This is the URL of the YouTube video.

  2. preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match); - This is the regular expression used to match the YouTube video ID.

  3. echo $match[1]; - This is the code to output the YouTube video ID.

Helpful links

Edit this code on GitHub