可能重复:
RegEx pattern to get the YouTube video ID from any YouTube URL
我已将youtube url存储在数据库中。我想从youtube url中仅获取youtube id。我只想从url中提取id(6FjfewWAGdE)。
$youtubeVal=http://www.youtube.com/embed/6FjfewWAGdE?feature=player_detailpage
答案 0 :(得分:1)
你可以通过
来做到这一点var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match&&match[2].length==11){
return match[2];
}
答案 1 :(得分:0)
Youtube网址有多种格式(使用embed /< id>或手表?v =< id>)。找到您想要理解的URL类型,并构建正则表达式以正确提取它们。
答案 2 :(得分:0)
这是 PHP :
中一个有效的非正则表达式解决方案function GetYoutubeID($url) {
$temp = parse_url($url);
if(isset($temp['query'])) {
parse_str($temp['query'], $temp2);
if(isset($temp2['v'])) {
return $temp2['v'];
}
}
if(isset($temp['path'])) {
$temp2 = explode("/", $temp['path']);
foreach($temp2 as $value) {
if(strlen($value) == 11 || strlen($value) == 10) {
return $value;
}
}
}
return "no ID?";
}
echo $youtubeID = GetYoutubeID('http://www.youtube.com/embed/6FjfewWAGdE?feature=player_detailpage') . "\n";
echo $youtubeID = GetYoutubeID('https://www.youtube.com/embed/6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('https://youtube.com/embed/6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('http://www.youtube.com/watch?v=6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('http://www.youtube.com/watch?v=6FjfewWAGdE&feature=player_detailpage') . "\n";
echo $youtubeID = GetYoutubeID('www.youtu.be/6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('youtu.be/6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('youtube.com/watch?v=6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('https://www.youtube.com/watch?v=6FjfewWAGdE&feature=youtu.be') . "\n";
使用以下内容替换函数的全部内容,以使用更好看的解决方案(Regular expression):
preg_match('/^(http:\/\/|https:\/\/|.*?)(www.|.*?)(youtube.com|youtu.be)\/(embed\/|watch\?v=|.*?)(.*?)(\?|\&|$)/is', $url, $matches);
if(isset($matches[5])) {
return $matches[5];
}
return "no ID?"
正则表达式解决方案也适用于 Javascript :
function GetYoutubeID(url) {
var regExp = /^(http:\/\/|https:\/\/|.*?)(www.|.*?)(youtube.com|youtu.be)\/(embed\/|watch\?v=|.*?)(.*?)(\?|\&|$)/;
var match = url.match(regExp);
if (match){
return match[5];
}
return "no ID?";
}
console.log(GetYoutubeID('http://www.youtube.com/embed/6FjfewWAGdE?feature=player_detailpage'));
console.log(GetYoutubeID('http://www.youtube.com/embed/6FjfewWAGdE?feature=player_detailpage'));
console.log(GetYoutubeID('https://www.youtube.com/embed/6FjfewWAGdE'));
console.log(GetYoutubeID('https://youtube.com/embed/6FjfewWAGdE'));
console.log(GetYoutubeID('http://www.youtube.com/watch?v=6FjfewWAGdE'));
console.log(GetYoutubeID('http://www.youtube.com/watch?v=6FjfewWAGdE&feature=player_detailpage'));
console.log(GetYoutubeID('www.youtu.be/6FjfewWAGdE'));
console.log(GetYoutubeID('youtu.be/6FjfewWAGdE'));
console.log(GetYoutubeID('youtube.com/watch?v=6FjfewWAGdE'));
console.log(GetYoutubeID('https://www.youtube.com/watch?v=6FjfewWAGdE&feature=youtu.be'));
答案 3 :(得分:-1)
您可以随时尝试
youtubeVal.substring(29, 39);