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 an exact string?
- How to match a single quote in PHP regex?
- How to match a double quote in PHP regex?
- How to use an "or" condition in PHP regex?
- How to use PHP regex to match special characters?
- How to remove all non-numeric characters using PHP regex?
- How to match a space using PHP regex?
- How to use PHP regex to match tab?
- How to match a plus sign in PHP regex?
- How to use named capture groups in PHP regex?
See more codes...