2010-09-03 150 views
1

我在PHP中創建了Twitter結果列表,我已經使用PHP將字符串中的文本鏈接返回到可點擊鏈接而不是純文本。將Twitter哈希標籤變成鏈接並鏈接到可點擊的鏈接

在Twitter的一些結果中,字符串包含散列標籤,簡單的文字前綴爲#字符。

我想要做的就是拿hastag並將其轉換爲可點擊的鏈接。

例如:

Hello my name is Dan, and im working with the #twitter api 

,我想變成:

Hello my name is Dan, and im working with the <a href="http://search.twitter.com/search?q=%23twitter">#twitter</a> api 

注意,在URL我有#改爲23% - 我想編碼或解碼。

而且....

林已經在使用下面的代碼字符串中創建可點擊的鏈接,是有可能的兩個正則表達式的結合?

這是我的PHP鏈接轉換爲可點擊的鏈接:

  //Convert links in string to links 
      preg_match('/(http:\/\/[^\s]+)/', $row["content"], $text); 
      $hypertext = "<a target='_blank' href=\"". $text[0] . "\">" . $text[0] . "</a>"; 
      $newString = preg_replace('/(http:\/\/[^\s]+)/', $hypertext, $row["content"]); 

回答

10
$str = preg_replace('/\#([a-z0-9]+)/i', '<a href="http://search.twitter.com/search?q=%23$1">#$1</a>', $str); 

編輯

在兩種不同的模式方面,只是做:

$str = preg_replace(array($url_pattern, $hash_pattern), array($url_replacement, $hash_replacement), $str);