You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP YouTube链接转嵌入函数报错:$youtube_id未定义

解决YouTube链接转嵌入格式函数的未定义变量错误

问题根源是当传入的链接不匹配任何正则时,$youtube_id变量从未被声明,直接判断!$youtube_id会触发未定义变量错误,而非预期的返回null。

修复步骤:

  • 先初始化$youtube_id为null,确保变量始终存在
  • 在生成嵌入链接前校验$youtube_id,为空则返回null

修改后的完整函数代码:

public function getYoutubeEmbedUrl()
{
    $youtube_id = null; // 初始化变量,避免未定义错误
    $shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
    $longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))([a-zA-Z0-9_-]+)/i';

    if (preg_match($longUrlRegex, $this->video_link, $matches)) {
        $youtube_id = $matches[count($matches) - 1];
    }

    if (preg_match($shortUrlRegex, $this->video_link, $matches)) {
        $youtube_id = $matches[count($matches) - 1];
    }
    
    if (!$youtube_id) {
        return null;
    }
    
    return 'https://www.youtube.com/embed/' . $youtube_id ;
}

说明:

  • 提前初始化$youtube_id = null,确保无论是否匹配成功,变量都已声明
  • 校验逻辑放在变量赋值之后、返回嵌入链接之前,此时判断!$youtube_id不会触发错误
  • 当链接格式无效时,函数会返回null,避免后续使用时出现问题

内容的提问来源于stack exchange,提问作者broken heart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:47:07