我的目标是获取包含主题标签的字符串并返回所有主题标签.
我的功能:
function get_hashtags($text)
{
preg_match("/(^|\s)#(\w*[a-zA-Z_]+\w*)/", $text, $matches);
return $matches;
}
Run Code Online (Sandbox Code Playgroud)
目前我试试
$text = "yay this is #my comment and it's #awesome and cool";
$tag = get_hashtags($text);
print_r($tag);
Run Code Online (Sandbox Code Playgroud)
我得到:数组([0] => #my [1] => [2] =>我的)
我只想返回一个数组,如
array('tag1', 'tag2', 'tag3');
Run Code Online (Sandbox Code Playgroud)
没有实际的#
我做错了什么,我该如何解决?
谢谢
编辑:有人发布anaswer但它消失了,这正是我想要的,但现在我得到一个错误,代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
错误是:未定义的偏移量:2
我该如何解决?
尝试使用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]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
115 次 |
| 最近记录: |