I'd like to get a youtube channel ID or name from a youtube URL with a single regex. URLs can be vary like:
(#1 .../c/{name}) https://www.youtube.com/c/aespa
or
(#2 .../{name}) http://www.youtube.com/GIRLSGENERATION
or
(#3 .../channel/{ID}) https://www.youtube.com/channel/UCzgxx_DM2Dcb9Y1spb9mUJA/featured
What I already have now is do the job for case #1 and #3:
preg_match('/(?:(?:http|https):\/\/)?(?:www\.)?(?:youtube\.com)\/(channel|c)\/(?<name>[A-Za-z0-9-_\.]+)/im', $url, $matches);
I'd be great if the /channel|c
part could be optional so the case #2 will work too. It might be a problem that regex must check for /channel|c
first, and if there is no matches, it should check the URL against the /channel|c
part (Otherwise, /c
or /channel
string will be considered as name parameter).
Any advise appreciated!
Here is one solution which uses a regex pattern having an alternation to cover the three expected types of YouTube URL:
$inputs = ["https://www.youtube.com/c/aespa", "http://www.youtube.com/GIRLSGENERATION", "https://www.youtube.com/channel/UCzgxx_DM2Dcb9Y1spb9mUJA/featured"];
$names = [];
foreach ($inputs as $input) {
preg_match_all("/https?:\/\/www\.youtube\.com\/(?:channel\/(.*?)\/featured|(?:.*\/)*(.+))/", $input, $matches);
array_push($names, $matches[1][0] ?: $matches[2][0]);
print_r($matches);
}
print_r($names);
This prints:
Array
(
[0] => aespa
[1] => GIRLSGENERATION
[2] => UCzgxx_DM2Dcb9Y1spb9mUJA
)
For an explanation of the regex, the first portion of the alternation attempts to match the more specific /channel/{...}/feature
variant. That failing, the regex attempts to match and capture the final component of the URL as being the name.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments