Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Convert Youtube URL to Embed URL

Tags:

regex

php

youtube

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

like image 978
thatemployee Avatar asked Oct 16 '25 20:10

thatemployee


1 Answers

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.

like image 126
Sebastian Schneider Avatar answered Oct 19 '25 10:10

Sebastian Schneider