How can I extract a YouTube ID from this URL?
https%253A%252F%252Fwww.youtube.com%252Fwatch%253Fv%253Dnn5hCEMyE-E
I tried this regex:
$url = $_GET["q"];
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);
Decode it first and use the second index ([1]
) of array matches
:
if(isset($_GET["q"]))
{
$url = urldecode(rawurldecode($_GET["q"]));
# https://www.youtube.com/watch?v=nn5hCEMyE-E
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);
echo $matches[1];
# nn5hCEMyE-E
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With