MyFault MyFault - 5 months ago 55
PHP Question

PHP: Remove http://, http://www, https://, https:// from String and get the Domain name and TLD

I would like to create a function in

PHP
that removes all inputs like

http://
https://
http://www.
https://www.
http://xyz.


from a given domain name like

example.com


and returns an array like this:

'name' => 'example'
'tld' => 'com'


Any ideas how to do that?

Answer

Try following regex:

(?:^|\s)(?:https?:\/\/)?(?:\w+(?=\.).)?(?<name>.*).(?<tld>(?<=\.)\w+)

See demo at https://regex101.com/r/lI2lB4/2

If you input is

www.google.com
mail.yahoo.com.in
http://microsoft.com
http://www.google.com
http://mail.yahoo.co.uk

Captured content will be:

MATCH 1
name       = `google`
tld        = `com`

MATCH 2
name       = `yahoo.com`
tld        = `in`

MATCH 3
name       = `microsoft`
tld        = `com`

MATCH 4
name       = `google`
tld        = `com`

MATCH 5
name       = `yahoo.co`
tld        = `uk`
Comments