Home > Backend Development > PHP Tutorial > How to Reliably Extract YouTube Video IDs Using `preg_match`?

How to Reliably Extract YouTube Video IDs Using `preg_match`?

Barbara Streisand
Release: 2024-12-02 07:24:10
Original
338 people have browsed it

How to Reliably Extract YouTube Video IDs Using `preg_match`?

Parse YouTube Video ID Using preg_match

In an attempt to extract the video ID from a YouTube URL using preg_match, a common yet unsuccessful approach utilizes a specific regular expression. However, this expression often results in the "Unknown modifier '[' error.

Improved Solution

To overcome this error, an enhanced regular expression with better versatility emerges as a superior alternative:

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

Key Features

  1. Flexibility: This comprehensive expression encompasses a wide range of YouTube URL formats, ensuring adaptability to various scenarios.
  2. Accounted URLs: It successfully extracts video IDs from URLs with the following variations:

    • youtu.be URLs
    • YouTube embed URLs
    • Regular YouTube URLs with 'v=' or 'e/' prefixes
    • URLs with additional content following the video ID
  3. Supported Platforms: The expression functions seamlessly with both YouTube.com and YouTube-nocookie.com URLs.
  4. Embed Code Compatibility: It gracefully handles embed codes, extracting the video ID despite their specific format.

Sample URL Matching

This versatile expression accurately matches and extracts video IDs from a diverse set of URLs, including:

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

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template