php - Youtube I.D parsing for new URL formats -
this question has been asked before , found this:
but i'm looking different.
i need match youtube i.d compatible possible youtube link formats. not exclusively beginning youtube.com.
for example:
http://www.youtube.com/watch?v=-wtimtchwui
http://www.youtube.com/v/-wtimtchwui?version=3&autohide=1
http://youtu.be/-wtimtchwui
http://www.youtube.com/oembed?url=http%3a//www.youtube.com/watch?v%3d-wtimtchwui&format=json
http://s.ytimg.com/yt/favicon-wtimtchwui.ico
http://i2.ytimg.com/vi/-wtimtchwui/hqdefault.jpg
is there clever strategy can use match video i.d -wtimtchwui
compatible these formats. i'm thinking character counting , matching =
?
/
.
&
characters.
i had deal php class wrote few weeks ago , ended regex matches kind of strings: or without url scheme, or without subdomain, youtube.com url strings, youtu.be url strings , dealing kind of parameter sorting. can check out at github or copy , paste code block below:
/** * check if input string valid youtube url * , try extract youtube video id it. * @author stephan schmitz <eyecatchup@gmail.com> * @param $url string string shall checked. * @return mixed returns youtube video id, or (boolean) false. */ function parse_yturl($url) { $pattern = '#^(?:https?://|//)?(?:www\.|m\.)?(?:youtu\.be/|youtube\.com/(?:embed/|v/|watch\?v=|watch\?.+&v=))([\w-]{11})(?![\w-])#'; preg_match($pattern, $url, $matches); return (isset($matches[1])) ? $matches[1] : false; }
test cases: https://3v4l.org/gedt0
javascript version: https://stackoverflow.com/a/10315969/624466
to explain regex, here's split version:
/** * check if input string valid youtube url * , try extract youtube video id it. * @author stephan schmitz <eyecatchup@gmail.com> * @param $url string string shall checked. * @return mixed returns youtube video id, or (boolean) false. */ function parse_yturl($url) { $pattern = '#^(?:https?://|//)?' # optional url scheme. either http, or https, or protocol-relative. . '(?:www\.|m\.)?' # optional www or m subdomain. . '(?:' # group host alternatives: . 'youtu\.be/' # either youtu.be, . '|youtube\.com/' # or youtube.com . '(?:' # group path alternatives: . 'embed/' # either /embed/, . '|v/' # or /v/, . '|watch\?v=' # or /watch?v=, . '|watch\?.+&v=' # or /watch?other_param&v= . ')' # end path alternatives. . ')' # end host alternatives. . '([\w-]{11})' # 11 characters (length of youtube video ids). . '(?![\w-])#'; # rejects if overlong id. preg_match($pattern, $url, $matches); return (isset($matches[1])) ? $matches[1] : false; }
Comments
Post a Comment