PHP - 将Youtube URL转换为嵌入URL

时间:2018-03-05 23:52:22

标签: php regex youtube

我正在尝试使用以下函数将标准Youtube网址转换为嵌入网址:

<?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();

但是在运行时我收到以下错误:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function getYoutubeEmbedUrl()

我不明白为什么我只有一个参数太少而且我提供了它?

Online Editable Demo

2 个答案:

答案 0 :(得分:1)

如果您在PHP中定义一个函数,则非全局变量在函数中可访问。

因此,您必须提供该功能的参数的网址(您已将其定义为$url)。

工作解决方案:

<?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;
  

我不明白为什么我只有一个参数太少而且我提供了它?

始终必须通过方法调用提供PHP函数的参数。函数不使用预定义变量。

答案 1 :(得分:-1)

我认为当你执行函数&#34; getYoutubeEmbedUrl()&#34;时,你不会传递参数。在最后一行。

尝试&#34; echo getYoutubeEmbedUrl($ url);&#34;