3

I am currently using regex code to separate YT video ids. The reason I am using regex is that yt video URLs vary in many formats. I have built a regex that will pretty much detect the ID of almost all YT url formats except the one below. I have tried modifying it but no luck. Is there a way to have Regex strip the id from the URL below?

http://www.youtube.com/watch?feature=v-feature&v=317a815FLWQ

Regex:

('~https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/| youtube\.com\S*[^\w\-\s])([\w\-]{11})(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>| </a>))[?=&+%\w]*~ix','http://www.youtube.com/watch?v=$1',$url);

4 Answers4

3

How about a string operation? you would to find "v=" and start reading till the next "&" ? that would give you the video id and you can easily create the URL later

kommradHomer
  • 4,127
  • 5
  • 51
  • 68
0

FYI I use this code which works for all of the variations I have been able to find:

    function getYouTubeId($url)
    {
        $pattern = '#^(?:https?://|//)?(?:www\.|m\.)?(?:youtu\.be/|youtube\.com/(?:embed/|v/|watch\?v=|watch\?.+&v=))([\w-]{11})(?![\w-])#';
        preg_match($pattern, $url, $matches);
        return (isset($matches[1])) ? $matches[1] : false;
    }

Tested with these variations:

http://www.youtube.com/watch?v=-wtIMTCHWuI
http://www.youtube.com/v/-wtIMTCHWuI?version=3&autohide=1
http://youtu.be/-wtIMTCHWuI
https://www.youtube.com/embed/-wtIMTCHWuI

Originally found the function from this post a while ago.

Community
  • 1
  • 1
Josh
  • 847
  • 9
  • 17
-1

Why don't you just

$url = "http://www.youtube.com/watch?feature=v-feature&v=317a815FLWQ&hello=ok";
$stop = strlen($url);
$pos = strpos($url,'v=')+2;
$x = strpos($url,'&',$pos);
if($x)
    {
    $x = $x - $pos;
    $stop = $x;
    }
$str = substr($url,$pos,$stop);
echo $str;

It basically always starts with a v= ....

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
-1

The following should work:

(&|\?)v=(\w*)(&|$)

It gets whatever starts with & or ?, then the id and then the next & or the end.

I don't know PHP much, but I can see that you are trying to replace strings. That shouldn't work completely. I think what you should do is that get the match with the following and add it to a string to build your own URL.

preg_match('(&|\?)v=(\w*)(&|$)', $url, $matches);
$res = 'http://www.youtube.com/watch?v=' + $matches[1]

And then $res will the URL that want.

Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115