PHP Regex to get youtube video ID?

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

<?php

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

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

Watch a course Learn object oriented PHP

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.