這是我正在使用的代碼;我從這裏找到了另一個答案,但我現在找不到它..
<?php
class VideoUrlParser{
private $video_code;
private $video_type;
private $success;
public function __construct($url = null, $type = null) {
$this->success = false;
if(!empty($url) && !empty($type)) {
$this->video_code = trim($url);
$this->video_type = trim($type);
$this->success = true;
return;
}
if(!empty($url)) {
$urls = parse_url(trim($url));
//url is http://youtu.be/xxxx
if($urls['host'] == 'youtu.be'){
$this->video_code = ltrim($urls['path'],'/');
$this->video_type = "youtube";
$this->success = true;
}
else if($urls['host'] == 'youtube.com' || $urls['host'] == 'www.youtube.com'){
$this->video_type = "youtube";
//url is http://www.youtube.com/embed/xxxx
if(strpos($urls['path'],'embed') == 1){
$this->video_code = end(explode('/',$urls['path']));
$this->success = true;
}
//http://www.youtube.com/watch?feature=player_embedded&v=m-t4pcO99gI
//url is http://www.youtube.com/watch?v=xxxx
else{
parse_str($urls['query'],$parts);
$this->video_code = $parts['v'];
$this->success = true;
}
}
else if(strpos($urls['host'],'youku.com') > 0){
$this->video_type = "youku";
$regExp = "#/(?:player.php/sid/|v_show/id_)([a-zA-Z0-9]+)(?:/|\\.)#";
if(preg_match($regExp, $urls['path'], $url_parts)){
$this->video_code = $url_parts[1];
$this->success = true;
}
}
//url is xxxx only
else if(strpos($url,'/')===false){
$this->video_code = $url;
$this->video_type = "unknown";
}
return;
}
}
public function success() {
return $this->success;
}
public function getVideoType() {
return $this->video_type;
}
public function getVideoCode() {
return $this->video_code;
}
public function getVideoURL() {
if($this->video_type == "youtube") {
return 'http://www.youtube.com/?v=' . $this->video_code;
} elseif($this->video_type == "youku") {
return "http://v.youku.com/v_show/id_" . $this->video_code . ".html";
}
}
public function getEmbedCode($rel, $width, $height) {
if($this->video_type == "youtube") {
return '<iframe src="http://www.youtube.com/embed/'.$this->video_code.'?rel='.$rel.'" frameborder="0" width="'.($width?$width:560).'" height="'.($height?$height:349).'"></iframe>';
} else if($this->video_type == "youku") {
return '<iframe width="'.($width?$width:560).'" height="'.($height?$height:349).'" src="http://player.youku.com/player.php/sid/'.$this->video_code.'/v.swf"></iframe>';
} else {
return "unknown video type in class.video_url_parser";
}
}
}