I used the following templates because YouTube also has the youtube-nocookie.com domain:
'@youtube(?:-nocookie)?\.com/watch[#\?].*?v=([^"\& ]+)@i', '@youtube(?:-nocookie)?\.com/embed/([^"\&\? ]+)@i', '@youtube(?:-nocookie)?\.com/v/([^"\&\? ]+)@i', '@youtube(?:-nocookie)?\.com/\?v=([^"\& ]+)@i', '@youtu\.be/([^"\&\? ]+)@i', '@gdata\.youtube\.com/feeds/api/videos/([^"\&\? ]+)@i',
In your case, this would only mean expanding existing expressions with optional (-nocookie) for the regular YouTube.com URL as follows:
if (preg_match('/youtube(?:-nocookie)\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
If you modify the proposed expression so that it does NOT contain the final $, it should work as you intended. I also added -nocookie.
function youtube_id_from_url($url) { $pattern = '%^# Match any YouTube URL (?:https?://)? # Optional scheme. Either http or https (?:www\.)? # Optional www subdomain (?: # Group host alternatives youtu\.be/ # Either youtu.be, |youtube(?:-nocookie)?\.com # or youtube.com and youtube-nocookie (?: # Group path alternatives /embed/ # Either /embed/ | /v/ # or /v/ | /watch\?v= # or /watch\?v= ) # End path alternatives. ) # End host alternatives. ([\w-]{10,12}) # Allow 10-12 for 11 char YouTube id. %x' ; $result = preg_match($pattern, $url, $matches); if (false !== $result) { return $matches[1]; } return false; }
teezee
source share