Web Development
/
Updated 07 Sep 2025
/
2 min read
Web applications sometimes need to extract a profile identifier from a social-media URL for normalization, imports, or display. PHP’s URL parsing functions are usually easier to maintain than one large regular expression because they let you validate the hostname and path separately.
A parseUsername Function The following example supports several common profile URL formats:
function parseUsername(string $url): string { $host = strtolower((string) parse_url($url, PHP_URL_HOST)); $path = trim((string) parse_url($url, PHP_URL_PATH), '/'); $supportedHosts = [ 'twitter.com', 'www.twitter.com', 'x.com', 'www.x.com', 'medium.com', 'www.medium.com', 'facebook.com', 'www.facebook.com', 'vimeo.com', 'www.vimeo.com', 'instagram.com', 'www.instagram.com', ]; if (!in_array($host, $supportedHosts, true) || $path === '') { return $url; } return explode('/', $path)[0]; } How It Works Parse the hostname and path