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:
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
Better use
parse_url
andparse_str
to parse the URL and query string:this worked for me.
I perfected regex from the leader answer. It also grabs the ID from all of the various URLs, but more correctly.
Also, it correctly handles the wrong IDs, which more than 11 characters.
http://www.youtube.com/watch?v=0zM3nApSvMgDw3qlxF
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.
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)
use below code
Use