Get YouTube Video ID


/ Published in: PHP
Save to your folder(s)

Return the YouTube video ID.


Copy this code and paste it in your HTML
  1. function _get_video_id( $url ) {
  2. if( preg_match( '/http:\/\/youtu.be/', $url, $matches) ) {
  3. $url = parse_url($url, PHP_URL_PATH);
  4. $url = str_replace( '/', '', $url);
  5. return $url;
  6.  
  7. } elseif ( preg_match( '/watch/', $url, $matches) ) {
  8. $arr = parse_url($url);
  9. $url = str_replace( 'v=', '', $arr['query'] );
  10. return $url;
  11.  
  12. } elseif ( preg_match( '/http:\/\/www.youtube.com\/v/', $url, $matches) ) {
  13. $arr = parse_url($url);
  14. $url = str_replace( '/v/', '', $arr['path'] );
  15. return $url;
  16.  
  17. } elseif ( preg_match( '/http:\/\/www.youtube.com\/embed/', $url, $matches) ) {
  18. $arr = parse_url($url);
  19. $url = str_replace( '/embed/', '', $arr['path'] );
  20. return $url;
  21.  
  22. } elseif ( preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#", $url, $matches) ) {
  23. return $matches[0];
  24.  
  25. } else {
  26. return false;
  27. }
  28. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.