Home >Backend Development >PHP Tutorial >How to Extract YouTube Video IDs from Various URLs Using PHP Regex?

How to Extract YouTube Video IDs from Various URLs Using PHP Regex?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 02:50:11428browse

How to Extract YouTube Video IDs from Various URLs Using PHP Regex?

Parse YouTube Video IDs with PHP Regex

To parse the video ID from a YouTube URL using PHP's preg_match, employ the following improved regular expression:

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

Benefits:

  • Universal Compatibility: This regex captures video IDs from various YouTube URL formats, including youtu.be, watch?v=, and embed codes.
  • Exception Handling: It ignores additional characters present after the video ID in the URL, ensuring reliable extraction.
  • Support for Alternate URLs: The regex also handles YouTube URLs hosted on youtube-nocookie.com.

Usage:

$subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{11})%i', $subject, $matches);

print "<pre class="brush:php;toolbar:false">";
print_r($matches);
print "
";

Sample Input/Output:

Input URL Output
http://youtu.be/dQw4w9WgXcQ z_AbfPXTKms
http://www.youtube.com/e/dQw4w9WgXcQ z_AbfPXTKms
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ z_AbfPXTKms
http://www.youtube-nocookie.com/watch?v=dQw4w9WgXcQ z_AbfPXTKms

The above is the detailed content of How to Extract YouTube Video IDs from Various URLs Using PHP Regex?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn