Here's the pure regex:
function getDomainFromUrl($url) { if (preg_match('/^(?:https?:\/\/)?(?:(?:[^@]*@)|(?:[^:]*:[^@]*@))?(?:www\.)?([^\/:]+)/', $url, $parts)) { return $parts[1]; } return false; // or maybe '', depending on what you need } getDomainFromUrl("http://abc.example.com/"); // abc.example.com getDomainFromUrl("http://www.example.com/"); // example.com getDomainFromUrl("abc.example.com"); // abc.example.com getDomainFromUrl(" username@abc.example.com "); // abc.example.com getDomainFromUrl("https://username: password@abc.example.com "); // abc.example.com getDomainFromUrl("https://username: password@abc.example.com :123"); // abc.example.com
You can try it here: http://sandbox.onlinephpfunctions.com/code/3f0343bbb68b190bffff5d568470681c00b0c45c
If you want to know more about regex:
^ matching must start from the beginning on the string (?:https?:\/\/)? an optional, non-capturing group that matches http:// and https:// (?:(?:[^@]*@)|(?:[^:]*:[^@]*@))? an optional, non-capturing group that matches either *@ or *:*@ where * is any character (?:www\.)? an optional, non-capturing group that matches www. ([^\/:]+) a capturing group that matches anything up until a '/', a ':', or the end of the string
source share