Validate a youtube video link

I need to validate a string to see if it’s a valid youtube video link. Like or If the link is valid I would then post the correct <object> tags for the link and display the video.

Would the validating part best be made with a preg_match check? If so can you help me constructing a regular expression? :slight_smile:

Thanks in advance!

Edit: Fixed my regex and tested. I’m sure there is a better simpler regex out there.

$link = '';
$link = '';

if (preg_match('@^(?:http://(?:www\\.)?\\?v=|v/)([a-zA-Z0-9_]*)@', $link, $match)) {
    print 'true';
} else {
    print 'false';

Ah thanks alot man! Appreciate it really!

Hmm I noticed that the videocode can contain a hyphen aswell… how do you add that to the regex? ([a-zA-Z0-9_-]*) ?


Ah does it matter if it’s at the beginning of the regex or at the end (like I wrote?)

Not really but at the end you have to escape it so for example:

If i was storing this in a DB or someplace I would strip everything but “mw2fA4Z1f98” and build the rest when its being displayed.