-1

I am using the following code to get youtube code in a long script. It works with this link

"bla bla bla bla http://www.youtube.com/watch?v=kkLTxsAhURw bla bla" but it does not work in this link ""bla bla bla bla http://www.youtube.com/watch?v=3YDz-ftqr1g bla bla"

It gets '3YDz' before the - but not the rest.. How can i get all code from the second link? Thanks.

preg_match('~v=([A-Za-z0-9]+)~', $txt, $match); 

4 Answers4

0

A little edit:

preg_match('@v=([\-A-Za-z0-9]+)@', $txt, $match); 
AndiPower
  • 853
  • 10
  • 20
0

As others said but you can shorten the regx a bit.

preg_match('\v=([-\w]+)\', $txt, $match); 

Demo

http://regex101.com/r/tM2hU3/1

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
0

The other answers will tend to work, however this is a somewhat more robust regex:

<?php
$string = "This is video on youtube **http://www.youtube.com/watch?v=wKTBUmrwYDs**";

preg_match( '#http(s?)://(((www\.)?youtube\.com)|(youtu\.be))/((watch.*(\?|\&)v=([^&]+))|((embed/)?([a-z0-9\-_]+))|)#i' , $string , $matches );

$youtube_id = array_pop( $matches );
oliakaoil
  • 1,615
  • 2
  • 15
  • 36
0

This question has been asked on SO many times before...

Here is one with an answer that should work for you as well: parse youtube video id using preg_match

The regex:

if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
    $video_id = $match[1];
}
Community
  • 1
  • 1
Benjam
  • 5,285
  • 3
  • 26
  • 36