Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Regex to get YouTube Video ID
In PHP, you can extract YouTube video IDs from URLs using the parse_url() and parse_str() functions or regular expressions. The parsing approach is more reliable for standard YouTube URLs.
Using parse_url() and parse_str()
The most straightforward method uses built-in PHP functions to parse the URL query parameters −
<?php
$url = "https://www.youtube.com/watch?v=VX96I7PO8YU";
parse_str(parse_url($url, PHP_URL_QUERY), $my_array);
echo $my_array['v'];
?>
VX96I7PO8YU
The parse_url() function extracts the query string, while parse_str() converts it into an associative array where the video ID is stored in the 'v' key.
Using Regular Expression
For more complex YouTube URL formats, regex provides better flexibility −
<?php
function getYouTubeVideoId($url) {
$pattern = '/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/';
preg_match($pattern, $url, $matches);
return isset($matches[1]) ? $matches[1] : null;
}
$url1 = "https://www.youtube.com/watch?v=VX96I7PO8YU";
$url2 = "https://youtu.be/VX96I7PO8YU";
echo "Standard URL: " . getYouTubeVideoId($url1) . "<br>";
echo "Short URL: " . getYouTubeVideoId($url2);
?>
Standard URL: VX96I7PO8YU Short URL: VX96I7PO8YU
Comparison
| Method | Pros | Cons |
|---|---|---|
parse_url() |
Simple, reliable for standard URLs | Limited to query parameter format |
| Regular Expression | Handles multiple URL formats | More complex, requires careful pattern design |
Conclusion
Use parse_url() and parse_str() for standard YouTube URLs, or regex for handling multiple URL formats. Both methods effectively extract the 11-character video ID needed for YouTube integration.
