我正在尝试使用以下函数将标准 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()
我不明白为什么我只有一个参数并且我提供了参数却太少了??
最佳答案
如果您在 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/