Extracting Twitter hashtag from string in PHP

Zeid Selimovic picture Zeid Selimovic · Jun 13, 2012 · Viewed 12.4k times · Source

I need some help with twitter hashtag, I need to extract a certain hashtag as string variable in PHP. Until now I have this

$hash = preg_replace ("/#(\\w+)/", "<a href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet_text);

but this just transforms hashtag_string into link

Answer

nickb picture nickb · Jun 13, 2012

Use preg_match() to identify the hash and capture it to a variable, like so:

$string = 'Tweet #hashtag';
preg_match("/#(\\w+)/", $string, $matches);
$hash = $matches[1];
var_dump( $hash); // Outputs 'hashtag'

Demo