开发者

How to parse a youtube url to obtain the video or playlist ids?

I'm looking for a way to extract both (partials) youtube urls and single ids from a user input string.

This article How开发者_如何学编程 do I find all YouTube video ids in a string using a regex? got me going quite well but still i'm struggling a bit.

Is there a way to find both playlist and/or video ids from a strings from:

  • E4uySuFiCis
  • PLBE0103048563C552

Through:

  • ?v=4OfUVmfNk4E&list=PLBE0103048563C552&index=5
  • http://www.youtube.com/watch?v=4OfUVmfNk4E&list=PLBE0103048563C552&index=5


use:

$urlInfo = parse_url($url); // to get url components (scheme:host:query)

$urlVars = array();
parse_str($queryString, $urlVars); // to get the query vars 

check out the youtube api for more details on the format


I wrote a script to do this once where the YouTube URL is posted via "POST" under the key "l" (lowercase "L").

Unfortunately I never got round to incorporating it into my project so it's not been extensively tested to see how it does. If it fails it calls invalidURL with the URL as a parameter, if it succeeds it calls validURL with the ID from the URL.

This script may not be exactly what you're after because it ONLY retrieves the ID of the video currently playing - but you should be able to modify it easily.

if (isset($_POST['l'])) {
$ytIDLen = 11;
$link = $_POST['l'];
if (preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $link)) {
    $urlParts = parse_url($link);
    //$scheme
    //$host
    //$path
    //$query["v"]
    if (isset($urlParts["scheme"])) {
        if ( ($urlParts["scheme"] == "http" ) || ($urlParts["scheme"] == "https") ) {
            //$scheme = "http";
        } else invalidURL($link);
    } //else $scheme = "http";
    if (isset($urlParts["host"])) {
        if ( ($urlParts["host"] == "www.youtube.com") || ($urlParts["host"] == "www.youtube.co.uk") || ($urlParts["host"] == "youtube.com") || ($urlParts["host"] == "youtube.co.uk")) {
            //$host = "www.youtube.com";
            if (isset($urlParts["path"])) {
                if ($urlParts["path"] == "/watch") {
                    //$path = "/watch";
                    if (isset($urlParts["query"])) {
                        $query = array();
                        parse_str($urlParts["query"],$query);
                        if (isset($query["v"])) {
                            $query["v"] = preg_replace("/[^a-zA-Z0-9\s]/", "", $query["v"]);
                            if (strlen($query["v"]) == $ytIDLen) {
                                validUrl($query["v"]);
                            } else invalidURL($link);
                        } else invalidURL($link);
                    } else invalidURL($link);
                } else invalidURL($link);
            } else invalidURL($link);
        } else invalidURL($link);
    } else invalidURL($link);
} else invalidURL($link);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜