我目前正在使用函数getYoutubeId
提取youtube视频ID。函数通常会解析链接以找到其相应的ID。但我在为输入文本框分配php变量时遇到了问题,该变量将把url
传递到函数中,并最终提取ID。当将url粘贴到文本框中时,视频ID或Nothing会被回显。这里有一个例子:实物模型SITE
<input type="text" name="youtube" value="<? $sYoutubeUrl ?>">
<input type="submit" value="Parsen">
<?
function getYoutubeId($sYoutubeUrl) {
# set to zero
$youtube_id = "";
$sYoutubeUrl = trim($sYoutubeUrl);
# the User entered only the eleven chars long id, Case 1
if(strlen($sYoutubeUrl) === 11) {
$youtube_id = $sYoutubeUrl;
return $sYoutubeUrl;
}
# the User entered a Url
else {
# try to get all Cases
if (preg_match('~(?:youtube'.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu'.be/)([^"&?/ ]{11})~i', $sYoutubeUrl, $match)) {
$youtube_id = $match[1];
return $youtube_id;
}
# try to get some other channel codes, and fallback extractor
elseif(preg_match('~http://www.youtube.com/v/([A-Za-z0-9'-_]+).+?|embed'/([0-9A-Za-z-_]{11})|watch'?v'=([0-9A-Za-z-_]{11})|#.*/([0-9A-Za-z-_]{11})~si', $sYoutubeUrl, $match)) {
for ($i=1; $i<=4; $i++) {
if (strlen($match[$i])==11) {
$youtube_id = $match[$i];
break;
}
}
return $youtube_id;
}
else {
$youtube_id = "No valid YoutubeId extracted";
return $youtube_id;
}
}
}
echo (getYoutubeId($sYoutubeUrl));
?>
您需要将输入标记放入表单中,如下所示:
<form action="" method="POST">
<input type="text" name="youtube" value="" />
<input type="submit" value="Parsen" />
</form>
然后检查表格是否已提交并显示您的信息:
?>
if(isset($_POST['youtube'])){
// include that function here
print 'Result: ' . getYoutubeId($_POST['youtube']);
}
考虑使用parse_url()
从URL中获取视频ID,而不是使用正则表达式。