Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Twitter hashtag from string in PHP

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

like image 356
Zeid Selimovic Avatar asked Jun 13 '12 00:06

Zeid Selimovic


4 Answers

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

like image 63
nickb Avatar answered Oct 13 '22 19:10

nickb


I think this function will help you:

echo get_hashtags($string);



function get_hashtags($string, $str = 1) {
    preg_match_all('/#(\w+)/',$string,$matches);
    $i = 0;
    if ($str) {
        foreach ($matches[1] as $match) {
            $count = count($matches[1]);
            $keywords .= "$match";
            $i++;
            if ($count > $i) $keywords .= ", ";
        }
    } else {
        foreach ($matches[1] as $match) {
            $keyword[] = $match;
        }
        $keywords = $keyword;
    }
    return $keywords;
}
like image 26
Alvaro Avatar answered Oct 13 '22 20:10

Alvaro


As i understand you are saying that in text/pargraph/post you want to show tag with hash sign(#) like this:- #tag and in url you want to remove # sign because the string after # is not sended to server in request so i have edited your code and try out this:-

$string="www.funnenjoy.com is best #SocialNetworking #website";    
$text=preg_replace('/#(\\w+)/','<a href=/hash/$1>$0</a>',$string);
echo $text; // output will be www.funnenjoy.com is best <a href=search/SocialNetworking>#SocialNetworking</a> <a href=/search/website>#website</a>
like image 3
Ravinder Payal Avatar answered Oct 13 '22 18:10

Ravinder Payal


Extract multiple hashtag to array

$body = 'My #name is #Eminem, I am rap #god, #Yoyoya check it #out';
$hashtag_set = [];
$array = explode('#', $body);

foreach ($array as $key => $row) {
    $hashtag = [];
    if (!empty($row)) {
        $hashtag =  explode(' ', $row);
        $hashtag_set[] = '#' . $hashtag[0];
    }
}
print_r($hashtag_set);
like image 2
Leong Chee Siong Avatar answered Oct 13 '22 18:10

Leong Chee Siong