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

Laravel Blade视图中如何替换指定字符串嵌入YouTube视频

Laravel Blade 中转换YouTube链接为嵌入地址的实现方法

你可以根据项目实际场景选择以下任意一种方案实现需求:

方案1:模型层统一处理(推荐)

将链接转换逻辑封装在Event模型的访问器中,后续全局调用嵌入地址时无需重复编写转换逻辑,维护成本更低。
在app/Models/Event.php文件中添加如下访问器代码:

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function videoEmbedUrl(): Attribute
{
    return Attribute::get(fn () => str_replace('watch?v=', 'embed/', $this->video));
}

修改Blade视图中的iframe代码,直接调用封装好的属性即可:

<iframe class="w-100" height="315" src="{{ $event->video_embed_url }}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

方案2:Blade视图内直接替换

如果仅在单个页面用到嵌入逻辑,无需修改模型,可直接在视图输出时调用Laravel内置的字符串替换函数处理链接,替换原有iframe的src属性值即可:

<iframe class="w-100" height="315" src="{{ str_replace('watch?v=', 'embed/', $event->video) }}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

补充兼容方案

如果后续用户可能录入YouTube短链接(如https://youtu.be/Vt-Wf7d0CFo格式),简单字符串替换会失效,可通过正则提取视频ID后拼接标准嵌入地址,适配更多链接格式:

@php
preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i', $event->video, $matches);
$videoId = $matches[1] ?? '';
@endphp
{{-- 加非空判断避免无效地址加载 --}}
@if($videoId)
<iframe class="w-100" height="315" src="https://www.youtube.com/embed/{{ $videoId }}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
@endif

内容的提问来源于stack exchange,提问作者Osama Amr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 23:00:55