Extracting Usernames from Social Media URLs with PHP
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
$host = strtolower((string) parse_url($url, PHP_URL_HOST)); $path = trim((string) parse_url($url, PHP_URL_PATH), '/');parse_url()separates the URL into useful components. Trimming/makes the first path segment easier to read. -
Allow only known hosts
The
$supportedHostslist prevents unrelated URLs from being treated as social-profile URLs merely because they contain a similar-looking path. -
Return the first path segment
return explode('/', $path)[0];For a URL such as
https://www.instagram.com/jane_doe/, the first path segment isjane_doe.
Usage Examples
echo parseUsername("https://twitter.com/johndoe");
// johndoe
echo parseUsername("https://www.instagram.com/jane_doe/");
// jane_doe
echo parseUsername("https://medium.com/@writer");
// @writer
Some platforms also use non-username profile formats. For example, a Facebook URL such as https://facebook.com/profile.php?id=1000123456789 uses a query parameter rather than a username path. If your application needs to support those formats, handle them explicitly instead of assuming every first path segment is a username.
Conclusion
When extracting profile identifiers from social-media URLs, parse and validate the URL structure rather than relying on a broad regular expression. A hostname allowlist plus platform-specific handling is easier to extend and reduces false matches as URL formats evolve.