I have this string " link " and I want to get only the ID, ie from "? v="
I have this string " link " and I want to get only the ID, ie from "? v="
You can use parse_url
to extract the fragments of a url and match it with parse_str
that converts a valid querystring to an associative array ( $param
).
<?php
$url = 'https://www.youtube.com/watch?v=Y3eZEtwQVI8&list=UUdm1fwk5iqteE0MVOBUuE8Q%22';
$itens = parse_url ($url);
parse_str($itens['query'], $params);
echo '<pre>';
print_r($params);
Output:
Array
(
[v] => Y3eZEtwQVI8
[list] => UUdm1fwk5iqteE0MVOBUuE8Q"
)
You can use explode
$video = "https://www.youtube.com/watch?v=jNQXAC9IVRw";
$id = explode("?v=", $video);
Other examples here
You can use regex
to extract the ID:
$patternRegex = "/http[s]?:\/\/www\.youtube\.com\/watch\?v=(\w+)/";
$urlYoutube = "https://www.youtube.com/watch?v=jNQXAC9IVRw";
preg_match($patternRegex, $urlYoutube, $matches);
See here to work with your example.
Explaining $patternRegex
:
/http[s]?:\/\/www\.youtube\.com\/watch\?v=
: This part looks for the start of the URL. [s]?
- Indicates that the character s can occur once or zero times. (\w+)/
: This part captures all alphanumeric characters and underscores that exist after the? = v to the end of the URL. You can use as any url format will work
function YoutubeID($url)
{
if(strlen($url) > 11)
{
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match))
{
return $match[1];
}
else
return false;
}
return $url;
}