Extracting Twitter hashtag from string in PHP

前端 未结 7 1152
离开以前
离开以前 2020-12-18 11:19

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         


        
相关标签:
7条回答
  • 2020-12-18 11:31

    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)
    
    0 讨论(0)
  • 2020-12-18 11:32

    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

    0 讨论(0)
  • 2020-12-18 11:42

    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;
    }
    
    0 讨论(0)
  • 2020-12-18 11:44

    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.

    0 讨论(0)
  • 2020-12-18 11:45

    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);
    
    0 讨论(0)
  • 2020-12-18 11:47

    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>
    
    0 讨论(0)
提交回复
热议问题