views:

184

answers:

4
Im 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.
A: 

you could try to use Regex

http://php.net/manual/en/function.preg-match.php

Robert
+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
Maybe you should make the `www.` part optional.
kitsched
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
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
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
@kitsched, Yeah I know. Oh well. I might tackle that another time, unless someone already has a solution. :D
Pjack
A: 

Use preg_match.

The pattern should be something like:

/(http\:\/\/www\.youtube\.com\/watch\?v=\w{11})/
kitsched
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
The poster asked for a PHP solution, and you appear to have provided one in C#.
Michael Petrotta