Tuesday, March 2, 2010

get youtube video id from url

i had a task to show some youtube videos on a site and had problems reading the entire url due to the # and other characters in a youtube channel. so i wrote my function below to get the youtube video id

/**
     * Return video id for a youtube url
     *
     * @param string $url
     * @return string
     */
   
   
    function getYoutubeVideoId( $url ){
       
        $id_param = "v="; //video id starts after the equal sign
        $id_length = 11; //length of video id
        $id_param_pos = strpos( $url, $id_param ); // get position of v from the video param
        $id_param_pos += 2; //add 2 spaces to get actual video id
        $video_id = substr( $url, $id_param_pos, $id_length ); //gets id from entire youtube url
       
        return $video_id;
    }

No comments: