Home > Backend Development > PHP Tutorial > How to Reliably Extract YouTube Video IDs Using Regular Expressions?

How to Reliably Extract YouTube Video IDs Using Regular Expressions?

Barbara Streisand
Release: 2024-12-03 17:50:15
Original
853 people have browsed it

How to Reliably Extract YouTube Video IDs Using Regular Expressions?

Parse YouTube Video ID Using preg_match

Attempting to derive the video ID from a YouTube URL using preg_match, an issue arises where the pattern provided leads to an "Unknown modifier '[' error." To address this, an alternative regular expression is offered that effectively captures video IDs across various URL formats.

The improved regular expression is as follows:

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

This pattern successfully matches the following URL formats:

  • Complete URL: http://www.youtube.com/watch?v=dQw4w9WgXcQ
  • Embed URL: http://www.youtube.com/embed/dQw4w9WgXcQ
  • Short URL: http://youtu.be/dQw4w9WgXcQ
  • Search URL: http://www.youtube.com/?v=dQw4w9WgXcQ
  • User URL: http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
  • Channel URL: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
  • Embedded URL (iframe): http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
  • Embedded URL (object): http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ

Utilizing this regex, the video ID can be reliably extracted from a variety of YouTube URLs.

The above is the detailed content of How to Reliably Extract YouTube Video IDs Using Regular Expressions?. 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