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
相关产品推荐
相关产品推荐

