2012-11-30 21 views
7

我有一個字符串,裏面有哈希標記,我試圖將標記拉出來我想我很近但是得到相同的結果如何從字符串中抽取以哈希標記(#)開頭的單詞到數組

$string = "this is #a string with #some sweet #hash tags"; 

    preg_match_all('/(?!\b)(#\w+\b)/',$string,$matches); 

    print_r($matches); 

這將產生

Array ( 
    [0] => Array ( 
     [0] => "#a" 
     [1] => "#some" 
     [2] => "#hash" 
    ) 
    [1] => Array ( 
     [0] => "#a" 
     [1] => "#some" 
     [2] => "#hash" 
    ) 
) 

我只想一個數組與哈希標籤開始每個字一個多維數組。

回答

14

這是可以做到由/(?<!\w)#\w+/至REGx它將工作

+0

非常感謝你。 。它的工作! – Nikz

+1

@Nikz非常歡迎... :)高興地幫助 –

+0

如何使用起始關鍵字提取所有世界? –

3

這就是preg_match_all一樣。你總是得到一個多維數組。 [0]是完整匹配,並且是[1]第一個捕獲組結果列表。

只需訪問$matches[1]獲取所需的字符串。 (您與描述無關的Array ([0] => Array ([0]轉儲是不正確的你得到一個子陣級。)

2

我覺得這個功能將幫助您:

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; 
} 
0

嘗試:

$string = "this is #a string with #some sweet #hash tags"; 
preg_match_all('/(?<!\w)#\S+/', $string, $matches); 
print_r($matches[0]); 
echo("<br><br>"); 

// Output: Array ([0] => #a [1] => #some [2] => #hash) 
相關問題