I'm retriving a youtube link from mysql db with this code

<?php
//echo $embed;
$yt_url=$embed;
function get_youtube_id_from_url($url)
    {
    if (stristr($url,'youtu.be/'))
        { preg_match('/(https|http):\/\/(.*?)\/([a-zA-Z0-9_]{11})/i', $url, $final_ID);return $final_ID[3]; }
    else 
        { preg_match('/(https|http):\/\/(.*?)\/(embed\/|watch\?v=|(.*?)&v=|v\/|e\/|.+\/|watch.*v=|)([a-zA-Z0-9_]{11})/i', $url, $IDD); return $IDD[5]; }
    }
$variable= get_youtube_id_from_url($yt_url);
?>

and extracting the id part of the link and placing it in this piece of code below

echo "<div align='center'><iframe src=\"//www.youtube.com/embed/" . $variable. "\" style=\"background: #fff;\" frameborder=\"0\" height=\"300\" scrolling=\"auto\" width=\"480\"></iframe></div>";

but am told the vedio dose not exit, please help

The pattern in the preg match is missing the dash -, it should be [a-zA-Z0-9_-], so change the first to:

'/(https|http):\/\/(.*?)\/([a-zA-Z0-9_-]{11})/i'

And the second to:

'/(https|http):\/\/(.*?)\/(embed\/|watch\?v=|(.*?)&v=|v\/|e\/|.+\/|watch.*v=|)([a-zA-Z0-9_-]{11})/i'

Because in case of links as $yt_url = "http://youtu.be/--9oAhOSwpg"; it will not work.

Try this

<?php
$yt_url="http://www.youtube.com/watch?v=ZvzwthHh-IQ";
function get_youtube_id_from_url($url)
    {
        preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);
        return $matches[1];
    }
$variable= get_youtube_id_from_url($yt_url);

echo "<div align='center'><iframe src=\"//www.youtube.com/embed/" . $variable. "\" style=\"background: #fff;\" frameborder=\"0\" height=\"300\" scrolling=\"auto\" width=\"480\"></iframe></div>";
?>
commented: This solved my problem before I asked +2

@Bachov Varghese code works like a charm :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.