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]; }
Key Features
Accounted URLs: It successfully extracts video IDs from URLs with the following variations:
Sample URL Matching
This versatile expression accurately matches and extracts video IDs from a diverse set of URLs, including:
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!