Last active
September 15, 2017 17:49
-
-
Save didicodethat/cfb38f0561318c7095fa9f58bc8ef493 to your computer and use it in GitHub Desktop.
A simple multipurpose php youtube url parser, this was used for specific needs so it is not really generic.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class YoutubeUrlParser | |
{ | |
const REGULAR_URL_FORMAT = '/^https?:\/\/(www\.)?youtube\.com\/watch/'; | |
const EMBEDDED_URL_FORMAT = '/^https?:\/\/(www\.)?youtube\.com\/embed/'; | |
const SHARE_URL_FORMAT = '/^https?:\/\/(www\.)?youtu\.be\//'; | |
private $originalUrl; | |
private $videoId; | |
public function __construct($url) | |
{ | |
$this->originalUrl = $url; | |
} | |
public function videoId() | |
{ | |
if($this->videoId) return $this->videoId; | |
$urlParts = parse_url($this->originalUrl); | |
$urlQuery = []; | |
$queryStr = array_get($urlParts, 'query', ''); | |
$pathUrl = array_get($urlParts, 'path', ''); | |
parse_str($queryStr, $urlQuery); | |
if($this->isRegular()){ | |
return $this->videoId = $urlQuery['v']; | |
} | |
if($this->isShareOrEmbedded()){ | |
$splittedPath = explode('/', $pathUrl); | |
return $this->videoId = end($splittedPath); | |
} | |
} | |
public function isValid(){ | |
return $this->isRegular() || $this->isShareOrEmbedded(); | |
} | |
private function isRegular() | |
{ | |
return preg_match(self::REGULAR_URL_FORMAT, $this->originalUrl); | |
} | |
private function isShareOrEmbedded() | |
{ | |
return preg_match(self::SHARE_URL_FORMAT, $this->originalUrl) | |
|| preg_match(self::EMBEDDED_URL_FORMAT, $this->originalUrl); | |
} | |
public function thumbnailUrl() | |
{ | |
return 'https://img.youtube.com/vi/' . $this->videoId() . '/hqdefault.jpg'; | |
} | |
public function embeddedUrl() | |
{ | |
return 'http://www.youtube.com/embed/' . $this->videoId(); | |
} | |
public function url() | |
{ | |
return 'https://youtu.be/'. $this->videoId(); | |
} | |
public function __toString() | |
{ | |
return $this->embeddedUrl(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment