【问题标题】:Get YouTube video id from embed iframe code从嵌入 iframe 代码中获取 YouTube 视频 ID
【发布时间】:2014-02-18 05:29:06
【问题描述】:
我想使用 preg_match 或 regex 从 YouTube 嵌入代码中获取 YouTube 视频 ID。举个例子
<iframe width="560" height="315" src="//www.youtube.com/embed/0gugBiEkLwU?rel=0" frameborder="0" allowfullscreen></iframe>
我要取ID0gugBiEkLwU
谁能告诉我怎么做。真的很适合你的帮助。
【问题讨论】:
标签:
php
regex
iframe
youtube
【解决方案2】:
你可以使用:
src="\/\/(?:https?:\/\/)?.*\/(.*?)\?rel=\d*"
查看演示Here
说明:
【解决方案3】:
我知道这已经很晚了,但我想出了一些东西给那些可能还在寻找的人。
由于并非所有 Youtube iframe src 属性都以“?rel=”结尾,并且有时可以以另一个查询字符串结尾或以双引号结尾,您可以使用:
/embed\/([\w+\-+]+)[\"\?]/
这会捕获“/embed/”之后和结束双引号/查询字符串之前的任何内容。选择可以包括任何字母、数字、下划线和连字符。
这是一个包含多个示例的演示:https://regex101.com/r/eW7rC1/1
【解决方案4】:
以下函数将从所有格式的 youtube url 中提取 youtube 视频 ID,
function getYoutubeVideoId($iframeCode) {
// Extract video url from embed code
return preg_replace_callback('/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/', function ($matches) {
// Remove quotes
$youtubeUrl = $matches[1];
$youtubeUrl = trim($youtubeUrl, '"');
$youtubeUrl = trim($youtubeUrl, "'");
// Extract id
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $youtubeUrl, $videoId);
return $youtubeVideoId = isset($videoId[1]) ? $videoId[1] : "";
}, $iframeCode);
}
$iframeCode = '<iframe width="560" height="315" src="http://www.youtube.com/embed/0gugBiEkLwU?rel=0" frameborder="0" allowfullscreen></iframe>';
// Returns youtube video id
echo getYoutubeVideoId($iframeCode);