2012-09-26 24 views
0

我的目標是獲取包含井號標籤的字符串並返回所有井號標籤。在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

我該如何解決?

回答

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]); 
0

您需要使用preg_match_all如果你希望所有的標籤了。 preg匹配函數的工作方式雖然總是會返回完整的匹配以及您試圖捕獲的內容,因此您無法直接返回$matches

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

    return $matches[2]; 

} 
0
preg_match_all('/(?<=\#)[^\s]+/', $text, $matches); 

您指定的$text值,$matches[0]將使用負向後看,它匹配的哈希值,但是從結果中排除只包含一個哈希後話。

[^\s]+你基本上可以用任何東西取代,在這個例子中,將匹配任何非空白字符,如果你需要它來只匹配單詞字符和下劃線,你可以使用Tim的例子中的部分[a-zA-Z_]+