douyingbei1458 2012-07-11 21:18
浏览 58
已采纳

PHP用于显示来自YouTube网址的视频ID

I am currently trying to retrieve YouTube video IDs through url. I created a function getYoutubeVideoID that strips $url and finds the $sVideoID. The Problem is that when i echo the variable i get an empty value of $sVideoID. How come i am getting no value result for $sVideoID if i am assigning it the video ID?

<?php

if($_POST)
{

$url     = $_POST['yurl'];

function getYoutubeVideoID($url) {
    $sVideoID = preg_replace('~https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/| youtube\.com\S*[^\w\-\s])([\w\-]{11})      
        (?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>| </a>))[?=&+%\w-]*~ix','<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>',$url);
    return $sVideoID;
}

    $hth        = 300; //$_POST['yheight'];
    $wdth       = 500; //$_POST['ywidth'];


?>

<?
//Iframe code

echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.$sVideoID.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');

?>

<?
//Old way to embed code
echo htmlentities ('<embed src="http://www.youtube.com/v/'.$sVideoID.'" width="'.$wdth.'" height="'.$hth.'" type="application/x-shockwave-flash"  wmode="transparent" embed="" /></embed>');
}
?>
  • 写回答

2条回答 默认 最新

  • dqt20140129 2012-07-11 21:30
    关注

    Perhaps I am wrong, or maybe you haven't included all relevant data, but I do not see anywhere in your code where you execute the function you have created.

    Instead of what you are currently doing, try this:

    echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.getYoutubeVideoID($url).'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');
    

    You can't simply define a function and it will execute and assign variables.. what you have has the function, when it is executed, return a variable in it's place. As an example, you could assign $var the return value of your function:

    $var = getYoutubeVideoID($url);
    

    Instead of the very above, you could even try this:

    $sVideoID = getYoutubeVideoID($url);
    

    Lastly, instead of using regex as others have noted, you could use parse_url() in combination with parse_str() to get the data from your url:

    $arr = parse_url($url);
    parse_str($arr['query'], $output);
    echo $output['v'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么