Search code examples
phpregexurlpreg-matchtwitch

Extract Twitch ursername from url


I'm trying to validate if a given url is a twitch.tv one and then extract the channel name from it. I came up with this regex:

preg_match("/^[(http|https):\/\/www.twitch.tv\/]+((?:[a-zA-Z0-9][\w]{3,24}))$/", $url, $output_array);

I seems to work but only if the the first characters of the username are not one of these (w, t, p, s, h, c, v, b)

For example if I enter the url: https://www.twitch.tv/AchannelName It will output:

0=>https://www.twitch.tv/AchannelName

1=>AchannelName

But for the following url: https://www.twitch.tv/channelName` It will output:

0=>https://www.twitch.tv/channelName

1=>annelName

PS: I am using [a-zA-Z0-9] because the username cannot start with underscore.


Solution

  • This should do it

    ^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$
    

    Then use

     $4