4

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

1
  • 1
    The short url regex will not catch all youtube urls, as some have dashes in them and the regex will cut them off. Here's a fixed regex to work with dashes: $shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_\-]+)\??/i'; Commented Feb 27, 2020 at 0:43

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, thank you for explaining. I will accept as an answer when the time is up.
-1

I think you don't pass the argument when you execute the function "getYoutubeEmbedUrl()" on the last line.

try "echo getYoutubeEmbedUrl($url);"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.