W3docs

PHP Regex to get youtube video ID?

You can use the following regular expression to extract the YouTube video ID from a URL:

You can use the following regular expression to extract the YouTube video ID from a URL:

Example of a PHP regex to get youtube video ID

<?php

$url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=30';
$pattern = '%^ (?:https?://)? (?:www\.)? (?: youtu\.be/ | youtube\.com (?: /embed/ | /v/ | /watch\?v= ) ) ([\w-]{11}) %x';
$result = preg_match($pattern, $url, $matches);
if ($result) {
  $videoId = $matches[1];
  echo $videoId; // Outputs: dQw4w9WgXcQ
}

This regular expression checks the URL for different patterns that a YouTube video URL may have and extracts the video ID from it.

Note: This regular expression will only work for YouTube video URLs. If you need to extract the video ID from a URL of a different video hosting service, you will need to use a different regular expression. You can test the snippet by running the provided example, which includes a sample URL with a query parameter and outputs the extracted ID.