Home >Backend Development >PHP Tutorial >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]; }
This pattern successfully matches the following URL formats:
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!