我的目標是獲取包含井號標籤的字符串並返回所有井號標籤。在PHP中用正則表達式返回所有的hastags?
我的功能:
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] =>#我的[1] => [2] =>我的)
我只是想返回一個數組如
array('tag1', 'tag2', 'tag3');
沒有實際#
我在做什麼錯,我該如何解決?
謝謝
編輯: 有人貼出了anaswer但disapeared,這正是我想要的不過現在我得到一個錯誤,代碼:
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
我該如何解決?