parse youtube video id using preg_match

2019-01-01 01:53发布

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&NR=1";

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

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

?>

Cheers

10条回答
萌妹纸的霸气范
2楼-- · 2019-01-01 02:12

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

$subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";
$url = parse_url($subject);
parse_str($url['query'], $query);
var_dump($query);
查看更多
梦醉为红颜
3楼-- · 2019-01-01 02:16

this worked for me.

$yout_url='http://www.youtube.com/watch?v=yxYjeNZvICk&blabla=blabla';

$videoid = preg_replace("#[&\?].+$#", "", preg_replace("#http://(?:www\.)?youtu\.?be(?:\.com)?/(embed/|watch\?v=|\?v=|v/|e/|.+/|watch.*v=|)#i", "", $yout_url));
查看更多
梦该遗忘
4楼-- · 2019-01-01 02:16

I perfected regex from the leader answer. It also grabs the ID from all of the various URLs, but more correctly.

if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[\w\-?&!#=,;]+/[\w\-?&!#=/,;]+/|(?:v|e(?:mbed)?)/|[\w\-?&!#=,;]*[?&]v=)|youtu\.be/)([\w-]{11})(?:[^\w-]|\Z)%i', $url, $match)) {
    $video_id = $match[1];
}

Also, it correctly handles the wrong IDs, which more than 11 characters.

http://www.youtube.com/watch?v=0zM3nApSvMgDw3qlxF

查看更多
ら面具成の殇う
5楼-- · 2019-01-01 02:19

This regex grabs the ID from all of the various URLs I could find... There may be more out there, but I couldn't find reference of them anywhere. If you come across one this doesn't match, please leave a comment with the URL, and I'll try and update the regex to match your URL.

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

Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)

It also works on the youtube-nocookie.com URL with the same above options.

It will also pull the ID from the URL in an embed code (both iframe and object tags)

查看更多
唯独是你
6楼-- · 2019-01-01 02:22

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]);
}
查看更多
明月照影归
7楼-- · 2019-01-01 02:24

Use

 preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#", $subject, $matches);
查看更多
登录 后发表回答