I have some code that check YouTube videos URL is valid in PHP.
<?php
$rx = '~
^(?:https?://)? # Optional protocol
(?:www\.)? # Optional subdomain
(?:youtube\.com|youtu\.be) # Mandatory domain name
/watch\?v=([^&]+) # URI with video id as capture group 1
~x';
$has_match = preg_match($rx, $vid1, $matches);
?>
it works similarly for this kind of URLs e.g.
https://www.youtube.com/watch?v=cpPG0bKHYKc
But it doesn't work correctly for some URLs such as:
As the comments in your regex state the protocol and subdomain are optional. Either form of the domain name is allowed. The last part of the regex is where you run into issues. The
/watch\?v=
then anything but an&
is required. Your second URL doesn't have/watch
in it. You could make the/watch
optional but thenyoutube.com/anything
would be allowed. I'd recommend putting the allowed formats in your alteration. Something like:I think would do it for you.
Demo: https://regex101.com/r/TKPtPD/1
The
[a-zA-Z\d]+
is also what appears to be the valid characters after theyoutu.be
domain. If more characters can be present you'll need to update that class.