views:

629

answers:

3

Hi,

I am attempting to parse the video ID of a youtube URL using preg_match. I found a regular expression on this site that appears to work;

(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+

As shown in this pic:

alt text

My PHP is as follows, but it doesn't work (gives Unknown modifier '[' error)...

<?
 $subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&amp;NR=1";

 preg_match("(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+", $subject, $matches);

 print "<pre>";
 print_r($matches);
 print "</pre>";

?>

Cheers

+3  A: 

Better use parse_url and parse_str to parse the URL and query string:

$subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&amp;NR=1";
$url = parse_url($subject);
parse_str($url['query'], $query);
var_dump($query);
Gumbo
Webbo
@Webbo: `parse_url` returns an array of the URL parts, so the URL path is also in there. You need to do some further case differentiation to what type the URL is.
Gumbo
I would rather use a regex to do it all in one
Webbo
+2  A: 

Use

 preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#", $subject, $matches);
Adam
Webbo
Webbo
A: 

use below code

$url = "" // here is url of youtube video
$pattern = getPatternFromUrl($url); //this will retun video id

function getPatternFromUrl($url)
{
$url = $url.'&';
$pattern = '/v=(.+?)&+/';
preg_match($pattern, $url, $matches);
//echo $matches[1]; die;
return ($matches[1]);
}
diEcho
This doesn't work for all youtube URL's
Webbo
it works ! i had tried? gimme any example that does not fit on this criteria?
diEcho
other related post`http://stackoverflow.com/questions/2164040/grab-the-youtube-video-`id-with-jquery-match`
diEcho
Webbo