0

我的目标是获取一个包含主题标签的字符串并返回所有主题标签。

我的功能:

function get_hashtags($text)
{
    preg_match("/(^|\s)#(\w*[a-zA-Z_]+\w*)/", $text, $matches);
    return $matches;

}

目前当我尝试

$text = "yay this is #my comment and it's #awesome and cool";
$tag = get_hashtags($text);
print_r($tag);

我得到:数组( [0] => #my [1] => [2] => my )

我只想返回一个数组,例如

array('tag1', 'tag2', 'tag3');

没有实际的#

我做错了什么,我该如何解决?

谢谢

编辑:有人发布了一个回答,但它消失了,这正是我想要的,但是现在我得到一个错误,代码:

function get_hashtags($text)
{
    $matches = array();
    preg_match_all("/(^|\s)#(\w*[a-zA-Z_]+\w*)/", $text, $matches);
    $result = array();
    foreach ($matches as $match) {
        $result[] = $match[2];
    }
    return $result;


}

错误是:未定义的偏移量:2

我该如何解决?

4

3 回答 3

5

尝试使用preg_match_all

$text = "yay this is #my comment and it's #awesome and cool";
preg_match_all("/(^|\s)#(\w*[a-zA-Z_]+\w*)/", $text, $matches); // updated to use original regex

var_dump($matches[1]);
于 2012-09-26T21:00:49.830 回答
0

preg_match_all如果您想要返回所有标签,则需要使用。preg 匹配函数的工作方式尽管它们总是会返回完整的匹配项以及您尝试捕获的内容,因此您将无法$matches直接返回。

function get_hashtags($text)
{
    preg_match_all("/(^|\s)#(\w*[a-zA-Z_]+\w*)/", $text, $matches);

    return $matches[2];

}
于 2012-09-26T21:00:59.283 回答
0
preg_match_all('/(?<=\#)[^\s]+/', $text, $matches);

对于$text您指定的值,$matches[0]将仅包含哈希后的单词,通过使用负向查找来匹配哈希,但将其从结果中排除。

您基本上可以用任何东西替换的部分[^\s]+,在本例中,它将匹配任何非空白字符,如果您需要它仅匹配单词字符和下划线,您可以使用 Tim 的示例[a-zA-Z_]+

于 2012-09-26T21:15:58.473 回答