0

Hi all I have a variable that is a YouTube url that is user-generated. There is a lot of threads on here about Regex and what not, but most are being executed in js. I want to run everything server-side in php, here is my simple function:

function youTubeID($url){
     $url = preg_replace('http://youtu.be/ Regex goes here', '', $url);
     return $url;
}

Markup:

<a href="http://youtu.be/yhXhVMKxnkY"><img src="http://img.youtube.com/vi/'.youTubeID($variable).'/0.jpg" /><img src="play.png" alt="Watch the video" title="Watch the video"/></a>

Question: Does anyone know the proper regex for http://youtu.be/ ?

I'm sure this is a quick answer, I'm not too savvy with regex. On a side note,does anyone know of any good resources where I can teach myself some good regex so I don't have to ask silly syntax questions like this? Cheers.

Scott Sword
  • 4,283
  • 5
  • 29
  • 37
  • possible duplicate of [parse youtube video id using preg_match](http://stackoverflow.com/questions/2936467/parse-youtube-video-id-using-preg-match) – PeeHaa Mar 08 '12 at 23:50
  • It's not clear from your function what it is you're actually trying to do – Madbreaks Mar 08 '12 at 23:50
  • Check out [my answer to a similar question](http://stackoverflow.com/a/5831191/433790). A good regex tutorial can be found at: [www.regular-expressions.info](http://www.regular-expressions.info/tutorial.html) – ridgerunner Mar 09 '12 at 00:51

2 Answers2

1

Why use a (relatively slow) RegEx at all?

$url = substr($url, strlen('http://youtu.be/'));

Obviously you have a set start point so no need to calculate it each time you call the function, but doing so here to demonstrate the idea.

Edit:

In case there's some reason you are required to use a RegEx:

$url = preg_replace('#http\://youtu\.be/#', '', $url);

Cheers

Madbreaks
  • 17,159
  • 7
  • 50
  • 64
0

Here you go:

/(?<=v(\=|\/))([-a-zA-Z0-9_]+)|(?<=youtu\.be\/)([-a-zA-Z0-9_]+)/m

edit: woops, you could say..

 function youTubeID($url){
     $pattern = "/(?<=v(\=|\/))([-a-zA-Z0-9_]+)|(?<=youtu\.be\/)([-a-zA-Z0-9_]+)/m";
     preg_match($pattern, $ytURL, $url);
     return $url[0];
     }

For testing it: http://gskinner.com/RegExr/

This is always bookmarked for me: http://www.regular-expressions.info/reference.html

matrices
  • 33
  • 4
  • Thanks for the info...for some reason is is doing just the opposite of what I'm after, it is stripping the ID and just printing http://youtu.be/ instead of everything that goes after that URL. I'm executing this as stated above. – Scott Sword Mar 08 '12 at 23:35