Another simple alternative would be using parse_url and parse_str functions.
function getYoutubeEmbedUrl ($url) {
$parsedUrl = parse_url($url);
# extract query string
parse_str(@$parsedUrl['query'], $queryString);
$youtubeId = @$queryString['v'] ?? substr(@$parsedUrl['path'], 1);
return "https://youtube.com/embed/{$youtubeId}";
}
Lets say we have these two links:
$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';
getYoutubeEmbedUrl($link1); // https://youtube.com/embed/NVcpJZJ60Ao
getYoutubeEmbedUrl($link2); // https://youtube.com/embed/NVcpJZJ60Ao
Explanation
parse_url function will extract link into 4 components: scheme, host, path, and query (see docs).
parse_url($link1);
// output
[
"scheme" => "https",
"host" => "www.youtube.com",
"path" => "/watch",
"query" => "v=NVcpJZJ60Ao",
]
The output of $link2 would be:
parse_url($link2);
// output
[
"scheme" => "https",
"host" => "www.youtu.be",
"path" => "/NVcpJZJ60Ao",
]
And parse_str will convert query string into an array (see docs).
parse_str('v=NVcpJZJ60Ao', $output);
// value of variable $output
[
"v" => "NVcpJZJ60Ao",
]