php-regexHow to use PHP regex to get a YouTube video ID?
Using PHP regex to get a YouTube video ID is a simple task. The following example code block will demonstrate how to do it:
$url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
echo $match[1];
The output of the example code will be:
dQw4w9WgXcQ
Code explanation
-
$url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
- This is the URL of the YouTube video. -
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
- This is the regular expression used to match the YouTube video ID. -
echo $match[1];
- This is the code to output the YouTube video ID.
Helpful links
More of Php Regex
- How to use PHP regex to match special characters?
- How to use PHP regex to match a zip code?
- How to get the first match when using regex in PHP?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match an exact string?
- How to match a single quote in PHP regex?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
See more codes...