Skip to content

Instantly share code, notes, and snippets.

@lenivene
Last active September 10, 2019 02:08
Show Gist options
  • Save lenivene/193b4b6b9fca9334ce9965310a46101e to your computer and use it in GitHub Desktop.
Save lenivene/193b4b6b9fca9334ce9965310a46101e to your computer and use it in GitHub Desktop.
Get YouTube url ID

Example code

$link = "https://www.youtube.com/watch?v=sOnqjkJTMaA";
$youtube_ID = get_youtube_ID( $link );

echo $youtube_ID;
<iframe width="560" height="315" src="https://www.youtube.com/embed/<?php echo $youtube_ID; ?>" frameborder="0" allowfullscreen></iframe>
<?php
/**
* Get YouTube URL ID
*
* @var string $link Link with https, http, sub domains or others domains related
* For Examples: [ m., gaming., www., youtube.com gaming.youtube.com, youtu.be ]
*
* @return string|boolean Return a ID if success; otherwise returns type boolean FALSE.
*/
function get_youtube_ID( $link ){
if( !isset( $link ) || empty( $link ) )
return false;
preg_match( '/(?:https?:\/\/|www\.|gaming\.|m\.|^)youtu(?:be\.com\/watch\?(?:.*?&(?:amp;)?)?v=|\.be\/)([\w‌​\-]+)(?:&(?:amp;)?[\w\?=]*)?/', $link, $match );
$ID = isset( $match[1] ) ? $match[1] : false;
return $ID;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment