DEV Community

loading...

Regex: Extract YouTube ID from URL

Matt Kenefick
Senior Engineer -- Learn to code first. Use libraries second.
・1 min read
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{11})%i', $url, $match)) {
    return $match[1];
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)