pcw
1
I need to validate a string to see if it’s a valid youtube video link. Like http://www.youtube.com/watch?v=mw2fA4Z1f98 or http://www.youtube.com/v/mw2fA4Z1f98. 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? 
Thanks in advance!
Edit: Fixed my regex and tested. I’m sure there is a better simpler regex out there.
$link = 'http://www.youtube.com/watch?v=mw2fA4Z1f98';
$link = 'http://www.youtube.com/v/mw2fA4Z1f98';
if (preg_match('@^(?:http://(?:www\\.)?youtube.com/)(watch\\?v=|v/)([a-zA-Z0-9_]*)@', $link, $match)) {
print 'true';
} else {
print 'false';
}
pcw
3
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_-]*) ?
pcw
5
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:
[FONT=monospace]([a-zA-Z0-9_\\-]*)[/FONT]
If i was storing this in a DB or someplace I would strip everything but “mw2fA4Z1f98” and build the rest when its being displayed.