Regex Twitter Username from different URLs in PHP

535 Views Asked by At

I've researched on Regex, and am trying to find the one which extracts the Username from various Twitter Urls. I've come with this one, but fails in the last example, can anyone help me?

/(https?:\/\/)?(www\.)?(twitter.com\/)?([@])?(\/status\/[0-9]{0,})?([a-z0-9_-])/ig

Tests are:

@Username <= "Username"
twitter.com/username <= "username"
www.twitter.com/username <= "username"
http://twitter.com/username <= "username"
https://twitter.com/username/status/608085900145197053 <= "username3" (FAILED)

Thank you!

2

There are 2 best solutions below

0
On

I've come with this solution:

/(?:https?:\/\/)?(?:mobile\.)?(?:www\.)?(?:twitter.com\/)?(?:[@])?([a-z0-9_-])(?:\/status\/(?:[a-z0-9]{0,}))?(?:\?.(\=.)?(\&.)?)?/ig

it works for all this cases:

@Username

twitter.com/username

www.twitter.com/username

http://www.twitter.com/username

http://twitter.com/username

https://twitter.com/username/status/608085900145197053

https://mobile.twitter.com/Us3rName?p=s

https://mobile.twitter.com/user_name1/status/608128181753671680?p=v

0
On

A better working solution when you're searching in some text is:

(?:https?:\/\/)?(?:mobile\.)?(?:www\.)?(?:twitter.com\/)(?:[@])?([A-Za-z0-9-_\.]+)(?:\/status\/(?:[a-z0-9]{0,}))?(?:\?.(?:\=.)?(?:\&.)?)?

The only matching group is the username itself and it's mandatory to have twitter.com/ in the url