Extracting Twitter hashtag from string in PHP

2020-03-07 05:54发布

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

7条回答
孤傲高冷的网名
2楼-- · 2020-03-07 06:21

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;
}
查看更多
神经病院院长
3楼-- · 2020-03-07 06:26

You can use preg_match_all() PHP function

preg_match_all('/(?<!\w)#\w+/', $description, $allMatches);

will give you only hastag array

preg_match_all('/#(\w+)/', $description, $allMatches);

will give you hastag and without hastag array

print_r($allMatches)
查看更多
Viruses.
4楼-- · 2020-03-07 06:32

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>
查看更多
叼着烟拽天下
5楼-- · 2020-03-07 06:33

You can extract a value in a string with preg_match function

preg_match("/#(\w+)/", $tweet_text, $matches);
$hash = $matches[1];

preg_match will store matching results in an array. You should take a look at the doc to see how to play with it.

查看更多
爷、活的狠高调
6楼-- · 2020-03-07 06:42

Here's a non Regex way to do it:

<?php

$tweet = "Foo bar #hashTag hello world";

$hashPos = strpos($tweet,'#');
$hashTag = '';

while ($tweet[$hashPos] !== ' ') {
 $hashTag .= $tweet[$hashPos++];
}

echo $hashTag;

Demo

Note: This will only pickup the first hashtag in the tweet.

查看更多
在下西门庆
7楼-- · 2020-03-07 06:43

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);
查看更多
登录 后发表回答