waynestate/parse-youtube-id

Parse the Video ID from a YouTube URL

1.0.0 2018-03-14 12:14 UTC

This package is auto-updated.

Last update: 2024-11-08 08:40:27 UTC


README

Master Build Status | Coverage Status

Given a YouTube video URL, parse out the video ID.

Usage

Install the package via composer:

composer require waynestate/parse-youtube-id

Parse full YouTube URL's

use Waynestate\Youtube\ParseId;

...

$youtube_id = ParseId::fromUrl('https://www.youtube.com/watch?v=yCjTG0rOIXQ');
echo $youtube_id; // 'yCjTG0rOIXQ'

Parse short YouTube URL's

$youtube_id = ParseId::fromUrl('https://youtu.be/yCjTG0rOIXQ');
echo $youtube_id; // 'yCjTG0rOIXQ'

Null strings or non-YouTube URL's return an empty string

$youtube_id = ParseId::fromUrl('');
echo $youtube_id; // ''

See /tests/UrlParseTest.php for all supported URL variations.

Regex

$pattern = '#^(?:https?://|//)?' # Optional URL scheme. Either http, or https, or protocol-relative.
         . '(?:www\.|m\.)?'      #  Optional www or m 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=,
         .       '|watch\?.+&v=' #      or /watch?other_param&v=
         .     ')'               #    End path alternatives.
         . ')'                   #  End host alternatives.
         . '([\w-]{11})'         # 11 characters (Length of Youtube video ids).
         . '(?![\w-])#';         # Rejects if overlong id.

Tests

composer test

Contributing

See CONTRIBUTING.md for details

Credit

Adapted from Stephan Schmitz at https://3v4l.org/GEDT0

About

Wayne State University (WSU) is an urban public research university located in Detroit, Michigan.