从YouTube获取视频网址并删除所有参数

时间:2011-03-31 17:17:30

标签: php regex

你好我怎么能删除这个字符串的任何内容并且只有XBH1dcHoL6Y?

<param name="movie" value="http://www.youtube.com/v/XBH1dcHoL6Y&rel=0&hl=en_US&feature=player_embedded&version=3">

我的目的是拥有这样的网址

http://www.youtube.com/watch?v=XBH1dcHoL6Y

这是我到目前为止所发现的(但我无法删除参数)

$url = "http://www.youtube.com/v/6n8PGnc_cV4";
$start = strpos($url,"v=");
echo 'http://www.youtube.com/v/'.substr($url,$start+2);

谢谢!

3 个答案:

答案 0 :(得分:2)

强制性单行:

echo end(explode('/', reset(explode('&', 'http://www.youtube.com/v/XBH1dcHoL6Y&rel=0&hl=en_US&feature=player_embedded&version=3'))));

修改: preg_match版本:

$string = '<embed src="http://www.youtube.com/v/XBH1dcHoL6Y&rel=0&hl=en_US&feature=player_embedded&-version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="390"></embed>';

$expr = "/<embed.*https?:\/\/www.youtube.com\/v\/([a-zA-Z0-9]+).*<\/embed>/";

if(preg_match($expr, $string, $matches))
  echo 'Matched: '.$matches[1];
else
  echo 'No match';

// returns "Matched: XBH1dcHoL6Y"

答案 1 :(得分:0)

试试这个:

$url = "http://www.youtube.com/v/XBH1dcHoL6Y&rel=0&hl=en_US";
$urlSplode = explode('/',$url);

$urlEnd = $urlSplode[count($urlSplode)-1];

$urlEndSplode = explode('&',$urlEnd);

$finalStr = $urlEndSplode[0];

echo "http://www.youtube.com/watch?v=$finalStr";

这是演示:

http://codepad.org/aoGLZSX0

答案 2 :(得分:0)

$urlTokens = explode("/", "http://www.youtube.com/v/XBH1dcHoL6Y&rel=0&hl=en_US&feature=player_embedded&version=3");  
$urlTokens = explode("&", $urlTokens[4]);
$url = $urlTokens[0]; // will output XBH1dcHoL6Y