我正在尝试使用以下函数将标准 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();
Run Code Online (Sandbox Code Playgroud)
但是,当运行它时,我收到以下错误:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function getYoutubeEmbedUrl()
Run Code Online (Sandbox Code Playgroud)
我不明白为什么当我只有一个并且我提供了它时我的参数太少了?
如果您在 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;
Run Code Online (Sandbox Code Playgroud)
我不明白为什么当我只有一个并且我提供了它时我的参数太少了?
函数的参数PHP始终必须通过方法调用提供。该函数不使用预定义变量。
| 归档时间: |
|
| 查看次数: |
4094 次 |
| 最近记录: |