PHP - 将 Youtube URL 转换为嵌入 URL

标签 php regex youtube

我正在尝试使用以下函数将标准 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()

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

Online Editable Demo

最佳答案

如果您在 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;

I am not understand why I have too few arguments when I only have one and I supplied it??

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

关于PHP - 将 Youtube URL 转换为嵌入 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49121332/

相关文章:

web-applications - YouTube 的动力是什么?

php - 简单的正则表达式问题 : How to find the first parentheses and get the content inside it?

regex - 如何在 Linux 中复制特定文件?

java - 模式与正则表达式不匹配

apache-flex - 在videodisplay flex中加载youtube视频

javascript - 使用 Youtube 的 iframe API 嵌入视频获取 "402 Payment Required"

PHP PDO 将数组转换为不同的格式

javascript - 如何将 bootstrap 年历与 mysql 库连接

php - mysql_num_rows 给出意外的结果

php - 如何在使用 mysql 插入期间连接和保存名字和姓氏?