Home >Backend Development >PHP Tutorial >How Can I Reliably Extract YouTube Video IDs from Various URLs using `preg_match`?

How Can I Reliably Extract YouTube Video IDs from Various URLs using `preg_match`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 01:33:10263browse

How Can I Reliably Extract YouTube Video IDs from Various URLs using `preg_match`?

Parsing YouTube Video ID using preg_match: An Extended Solution

The need to extract YouTube video IDs often arises in various web development scenarios. In this context, you may encounter the challenge of parsing the video ID from the URL using preg_match. While the regular expression you initially found might seem promising, it contains cryptic modifiers and groups that may lead to errors.

An enhanced approach is to utilize a more comprehensive regular expression that covers a wide range of YouTube URL formats. Here is an improved regular expression that we recommend:

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

This extended regular expression captures the following URL formats:

  • http://youtu.be/dQw4w9WgXcQ
  • http://www.youtube.com/embed/dQw4w9WgXcQ
  • http://www.youtube.com/watch?v=dQw4w9WgXcQ
  • http://www.youtube.com/?v=dQw4w9WgXcQ
  • http://www.youtube.com/v/dQw4w9WgXcQ
  • http://www.youtube.com/e/dQw4w9WgXcQ
  • http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
  • http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
  • http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
  • http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ

Additionally, this solution covers URLs on both "youtube.com" and "youtube-nocookie.com", as well as embedded URLs within iframe and object tags.

In summary, this refined approach provides a comprehensive solution for extracting YouTube video IDs from various URL formats, ensuring accuracy and ease of use.

The above is the detailed content of How Can I Reliably Extract YouTube Video IDs from Various URLs using `preg_match`?. 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