Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php parse url with regex

Tags:

regex

php

I have a PHP variable that contains one of two possible kind of URL:

$text = "http://www.youtube.com/v/wUJQPbALd68?version=3&autohide=1&autoplay=1";
$text = " http://www.youtube.com/watch?v=IcrbM1l_BoI 

How can I extract the id from the url for the two type? I think I have to use regex but I am a very newbie.

For example in first $text is wUJQPbALd68 and in the second is IcrbM1l_BoI .

Thanks a lot.

like image 730
michele Avatar asked Dec 25 '22 19:12

michele


1 Answers

/**
 * get youtube video ID from URL
 *
 * @param string $url
 * @return string Youtube video id or FALSE if none found. 
 * @authro hakre
 */
function youtube_id_from_url($url) {
    $pattern = 
        '%^# Match any youtube URL
        (?:https?://)?  # Optional scheme. Either http or https
        (?:www\.)?      # Optional www subdomain
        (?:             # Group host alternatives
          youtu\.be/    # Either youtu.be,
        | youtube\.com  # or youtube.com
          (?:           # Group path alternatives
            /embed/     # Either /embed/
          | /v/         # or /v/
          | /watch\?v=  # or /watch\?v=
          )             # End path alternatives.
        )               # End host alternatives.
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
        $%x'
        ;
    $result = preg_match($pattern, $url, $matches);
    if (false !== $result) {
        return $matches[1];
    }
    return false;
}

Youtube API - Extract video ID

like image 96
KHMKShore Avatar answered Jan 09 '23 01:01

KHMKShore