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:
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!