views:
184answers:
4Im trying to extract a YouTube link from just random text. e.g.
This is some random text and url is http://www.youtube.com/watch?v=-d3RYW0YoEk&feature=channel and I want to pull this URL out of this text in PHP. Can't seem to figure it out. Found a solution in another language but don't know how to convert it.
Thanks for the help.
+2
A:
You can use preg_match_all
to grab all such URL's as:
if(preg_match_all('~(http://www\.youtube\.com/watch\?v=[%&=#\w-]*)~',$input,$m)){
// matches found in $m
}
codaddict
2010-09-06 06:02:35
Maybe you should make the `www.` part optional.
kitsched
2010-09-06 06:12:16
This will also match `http://www.youtube.example.com/watch?v=…` or even `http://www.youtube.com is the YouTube’s URL; but http://example.com/watch?v=… isn’t.`.
Gumbo
2010-09-06 06:13:41
This works very well. Thank very much. I've been pulling my hair out. :) @kitsched I don't think ti will matter too much because YouTube will direct you to www.youtube.com if you just type in YouTube.com so the chance of the URL not have www when someone copies and paste is small.
Pjack
2010-09-06 06:33:27
Just to complicate things, there's one more case: when the user copies a URL from a tweet it looks like youtu.be/xxx :)
kitsched
2010-09-06 06:54:18
@kitsched, Yeah I know. Oh well. I might tackle that another time, unless someone already has a solution. :D
Pjack
2010-09-07 07:40:59
A:
Use preg_match
.
The pattern should be something like:
/(http\:\/\/www\.youtube\.com\/watch\?v=\w{11})/
kitsched
2010-09-06 06:03:27
A:
` private string GetYouTubeID(string youTubeUrl)
{
//Setup the RegEx Match and give it
Match regexMatch = Regex.Match(youTubeUrl, "^[^v]+v=(.{11}).*",
RegexOptions.IgnoreCase);
return regexMatch.Groups[1].Value;
} `
Wasim
2010-09-06 06:33:06
The poster asked for a PHP solution, and you appear to have provided one in C#.
Michael Petrotta
2010-09-06 18:01:47