I am trying to convert a standard Youtube URL to an Embed URL with the following function:
<?php
$url = 'https://www.youtube.com/watch?v=oVT78QcRQtU';
function getYoutubeEmbedUrl($url)
{
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))(\w+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
getYoutubeEmbedUrl();
However when running it I get the following error:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function getYoutubeEmbedUrl()
I am not understand why I have too few arguments when I only have one and I supplied it??
Online Editable Demo
If you define a function in PHP, non global variables are not accessible within the function.
Therefore you have to provide the URL as parameter of the function (which you've defined as $url
).
Working solution:
<?php
function getYoutubeEmbedUrl($url){
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))(\w+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
$url = 'https://www.youtube.com/watch?v=oVT78QcRQtU';
$embeded_url = getYoutubeEmbedUrl($url);
echo $embeded_url;
I am not understand why I have too few arguments when I only have one and I supplied it??
A argument of a PHP
function always has to be supplied via the method call. Predefined variables are not used by the function.
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