StackTips

How to Extract Twitter Username from Url

stacktips avtar

Written by

Editorial,  1 min read,  2.95K views, updated on Sept. 17, 2023

The following PHP code snippet extracts the twitter username from twitter URL using regular expressions. For example, if you pass the following url, it will output β€˜Stacktipsβ€˜.

twitter.com/Stacktips

Snippet:

if ( !function_exists( 'get_twitter_id_from_url' ) ){
	function get_twitter_id_from_url($url)
	{	
  	  if (preg_match("/^https?:\/\/(www\.)?twitter\.com\/(#!\/)?(?<name>[^\/]+)(\/\w+)*$/", $url, $regs)) {
  	    return $regs['name'];
  	  }
  	  return false;	  
  }
}
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.

Related posts

Let’s be friends!

πŸ™Œ Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!