RegEx pattern to get the YouTube video ID from any YouTube URL

后端 未结 9 1974
南方客
南方客 2020-11-27 17:48

Let\'s take these URLs as an example:

  1. http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player
  2. http://www.youtube.com/watch?v=8Gqqj
9条回答
  •  粉色の甜心
    2020-11-27 18:10

    if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
      $values = $id[1];
    } else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id)) {
      $values = $id[1];
    } else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id)) {
      $values = $id[1];
    } else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $id)) {
      $values = $id[1];
    }
    else if (preg_match('/youtube\.com\/verify_age\?next_url=\/watch%3Fv%3D([^\&\?\/]+)/', $url, $id)) {
        $values = $id[1];
    } else {   
    // not an youtube video
    }
    

    This is what I use to extract the id from an youtube url. I think it works in all cases.

    Note that at the end $values = id of the video

提交回复
热议问题