tags:

views:

53

answers:

3

Hi. I want to retrieve all hashtags from a tweet using a PHP function.

I know someone asked a similar question here, but there is no hint how exactly to implement this in PHP. Since I'm not very familiar with regular expressions, don't know how to write a function that returns an array of all hashtags in a tweet.

So how do I do this, using the following regular expression:

#\S*\w
+1  A: 

Try this regular expression:

/#[^\s]*/i

Running it PHP would look like:

preg_match_all('/#[^\s]*/i', $tweet_string, $result);

The result is an array containing all the hashtags in the Tweet (saved as "$result" - the third argument).

Lastly, check out this site. I've found it really handy for testing regular expressions. http://regex.larsolavtorvik.com/

EDIT: I tried your regular expression and it worked great too!

Wireblue
+1  A: 

Use the preg_match_all() function:

function get_hashtags($tweet)
{
    $matches = array();
    preg_match_all('/#\S*\w/i', $tweet, $matches);
    return $matches[0];
}
BoltClock
+2  A: 
$tweet = "this has a #hashtag a  #badhash-tag and a #goodhash_tag";

preg_match_all("/(#\w+)/", $tweet, $matches);

var_dump( $matches );

*Dashes are illegal chars for hashtags, underscores are allowed.

Cups
works fine, thanks!
snorpey