Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reg exp for youtube link

In a system that I'm developing I need to recognize the youtube link in the following format

[youtube]youtube url[/youtube]

for the moment I arrived at this regular expression:

#\[youtube\]http://www.youtube\.(.*)/watch\?v=([a-zA-Z0-9_-]*)\[\/youtube\]#s

But this pattern isn't able to recognize url like

[youtube]http://www.youtube.com/watch?v=s3wXkv1VW54&feature=fvst[/youtube]

Note the feature=fvst.

Some one can help me in recognize all possible youtube url?

like image 747
Luca Bernardi Avatar asked Feb 08 '10 10:02

Luca Bernardi


2 Answers

How about

|\[youtube\]http://www.youtube\.(.*?)/watch\?v=([a-zA-Z0-9_-]*)[%&=#a-zA-Z0-9_-]*\[\/youtube\]|s

EDIT: Changed the regex to keep only the video id inside parentheses.

like image 67
Tim Pietzcker Avatar answered Nov 06 '22 07:11

Tim Pietzcker


Notes:
I'd perform a case-insensitive match on URLs (/i)
. matches anything; use \. instead to match the URL
Also, "www." in Youtube URLs is optional.
Use (\.[a-z]+){1,2} instead of ".*" to match ".com", ".co.uk", .. after "youtube"

Assuming the "&feature" part is optional, the regex would be:

/\[youtube\]http:\/\/(www\.)?youtube(\.[a-z]+){1,2}\/watch\?v=([a-z0-9_-]*)(&feature=([a-z]+))?\[\/youtube\]/is

Assuming the "&feature" part is optional, AND there can be other parameters than "feature":

/\[youtube\]http:\/\/(www\.)?youtube(\.[a-z]+){1,2}\/watch\?v=([a-z0-9_-]*)(&([a-z]+)=([a-z0-9_-])+)*?\[\/youtube\]/is
like image 25
We Know Avatar answered Nov 06 '22 07:11

We Know