Home >Backend Development >PHP Tutorial >How to Extract YouTube Video IDs from Various URLs Using PHP Regex?
Parse YouTube Video IDs with PHP Regex
To parse the video ID from a YouTube URL using PHP's preg_match, employ the following improved regular expression:
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{11})%i', $url, $match)) { $video_id = $match[1]; }
Benefits:
Usage:
$subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1"; preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{11})%i', $subject, $matches); print "<pre class="brush:php;toolbar:false">"; print_r($matches); print "";
Sample Input/Output:
Input URL | Output |
---|---|
http://youtu.be/dQw4w9WgXcQ | z_AbfPXTKms |
http://www.youtube.com/e/dQw4w9WgXcQ | z_AbfPXTKms |
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ | z_AbfPXTKms |
http://www.youtube-nocookie.com/watch?v=dQw4w9WgXcQ | z_AbfPXTKms |
The above is the detailed content of How to Extract YouTube Video IDs from Various URLs Using PHP Regex?. For more information, please follow other related articles on the PHP Chinese website!