How to check YouTtube videos URL is validation now?

1.4k views Asked by At

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:

https://youtu.be/auz2t9nBcwU

1

There are 1 answers

1
chris85 On

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 then youtube.com/anything would be allowed. I'd recommend putting the allowed formats in your alteration. Something like:

^(?:https?://)?(?:www\.)?(?:youtube\.com/watch\?v=([^&\n]+)|youtu\.be/([a-zA-Z\d]+))$

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 the youtu.be domain. If more characters can be present you'll need to update that class.