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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-01 03:24:12185browse

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

Parsing YouTube Video ID Using preg_match

Problem:

Parsing the video ID from a YouTube URL using preg_match can be challenging, as shown by the original issue. The provided regular expression wasn't yielding the desired results due to syntax errors.

Solution:

A more robust solution to extract the video ID with preg_match is given in the provided answer:

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

This regular expression caters to various YouTube URL formats, including:

  • http://youtu.be/dQw4w9WgXcQ
  • http://www.youtube.com/embed/dQw4w9WgXcQ
  • http://www.youtube.com/watch?v=dQw4w9WgXcQ

Additionally, it handles the youtube-nocookie.com domain and video IDs embedded in iframe or object tags.

The above is the detailed content of How Can I Reliably Extract YouTube Video IDs from 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