Grab the video ID only from youtube's URLs

后端 未结 1 479
栀梦
栀梦 2021-01-26 22:07

How can I grab the video ID only from the youtube\'s URLs?

For instance,

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

sometime

1条回答
  •  遥遥无期
    2021-01-26 22:31

    You should never use regular expressions when the same thing can be accomplished through purpose-built functions.

    You can use parse_url to break the URL up into its segments, and parse_str to break the query string portion into a key/value array:

    $url = 'http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index'
    
    // break the URL into its components
    $parts = parse_url($url);
    
    // $parts['query'] contains the query string: 'v=Z29MkJdMKqs&feature=grec_index'
    
    // parse variables into key=>value array
    $query = array();
    parse_str($parts['query'], $query);
    
    echo $query['v']; // Z29MkJdMKqs
    echo $query['feature'] // grec_index
    

    The alternate form of parse_str extracts variables into the current scope. You could build this into a function to find and return the v parameter:

    // Returns null if video id doesn't exist in URL
    function get_video_id($url) {
      $parts = parse_url($url);
    
      // Make sure $url had a query string
      if (!array_key_exists('query', $parts))
        return null;
    
      parse_str($parts['query']);
    
      // Return the 'v' parameter if it existed
      return isset($v) ? $v : null;
    }
    

    0 讨论(0)
提交回复
热议问题