views:

623

answers:

3

I have a site that allows users to copy and paste the embeded video script that youtube provides and upload it to a database. I want to be able to check that this script is valid youtube script and not just random text that someone typed in. I believe this can be done with preg match. Any ideas?

+3  A: 

You could use:

preg_match('/^<object (?<width_height>width="[[:digit:]]+" height="[[:digit:]]+")><param name="movie" value=(?<url>"http:\/\/www.youtube.com\/v\/[^&]+&hl=[[:alpha:]]{2}&fs=1")><\/param><param name="allowFullScreen" value="true"><\/param><param name="(?<asa>allowscriptaccess)" value="always"><\/param><embed src=(?P=url) type="application\/x-shockwave-flash" (?P=asa)="always" allowfullscreen="true" (?P=width_height)><\/embed><\/object>$/', $yt);

but it would be better to just have them enter a URL (which is much easier to validate and parse), and generate this yourself.

Matthew Flaschen
+1 for suggestion about asking for URL rather than code.
Michal M
A: 

How would I do it if I allowed them to enter a URL?

A: 

To match URLs:

$pattern = '/.*youtube.*(v=|\/v\/)([^&\/]*).*/i';
preg_match($pattern, $video, $matches)
$videoId = $matches[2];

You can then use the $videoId to wrap into any YouTube URL format you want.

anushr