5

我需要一些关于 twitter 主题标签的帮助,我需要在 PHP 中提取某个主题标签作为字符串变量。直到现在我有这个

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

但这只是将 hashtag_string 转换为链接

4

7 回答 7

15

用于preg_match()识别哈希并将其捕获到变量中,如下所示:

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

演示

于 2012-06-13T00:13:52.603 回答
3

据我了解,您是说在 text/pargraph/post 中您想显示带有井号 (#) 的标签,如下所示:- #tag 和在 url 中您要删除 # 符号,因为之后的字符串#未在请求中发送到服务器所以我编辑了你的代码并试试这个: -

$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>
于 2014-04-02T06:18:25.433 回答
3

我认为这个功能会帮助你:

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;
}
于 2014-03-30T22:46:14.277 回答
2

提取多个主题标签到数组

$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);
于 2018-02-27T02:26:01.017 回答
2

你可以使用preg_match_all()PHP函数

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

只会给你 hastag 数组

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

会给你 hastag 并且没有 hastag 数组

print_r($allMatches)
于 2018-05-11T05:20:57.293 回答
1

您可以使用preg_match 函数提取字符串中的值

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

preg_match 将匹配结果存储在一个数组中。您应该查看文档以了解如何使用它。

于 2012-06-13T00:14:02.930 回答
0

这是一种非正则表达式的方法:

<?php

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

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

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

echo $hashTag;

演示

注意:这只会获取推文中的第一个主题标签。

于 2012-06-13T00:14:48.203 回答