PHP - 将Youtube链接转换为嵌入式链接

4
我将尝试使用以下函数将标准的Youtube URL转换为嵌入式URL:

我试图使用以下功能将标准的YouTube URL转换为嵌入式URL:

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

我不明白为什么我只有一个参数并且已经提供了它,但还是提示我参数太少?

在线可编辑演示


1
短网址正则表达式无法捕获所有YouTube网址,因为有些网址中有破折号,而正则表达式会将其截断。这是一个修复后的正则表达式,可以处理带有破折号的网址:$shortUrlRegex = '/youtu.be/([a-zA-Z0-9_-]+)??/i'; - rmmoul
2个回答

5

如果在 PHP 中定义一个函数,非全局变量将无法在函数内部访问。

因此,您需要将 URL 作为函数的参数提供(将其定义为$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
非常好,谢谢你的解释。时间到了我会接受作为答案。 - thatemployee

-1

我认为你在执行最后一行的函数"getYoutubeEmbedUrl()"时没有传递参数。

尝试使用"echo getYoutubeEmbedUrl($url);"。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接