2009-08-12 87 views
0

我需要一些幫助,改善這個功能,我解析Twitter中的鏈接。它爲hashtags和@replys創建鏈接。它一切正常,問題是如果hashtag或@reply在最後沒有空格的情況下有標點符號,它會被添加到HREF URL中。幫助preg_replace,停止在非alpa_numeric字符

例如,如果我推文「我非常喜歡#pizza和#pop」,#pizza的鏈接將會是錯誤的,因爲它會包含逗號。

我對Regex不太好,這讓我花了一段時間纔得到這個工作,所以任何幫助都會很棒!

function parse_tweet($description, $colour='', $external=false) { 
if ($external == true) $pre = 'http://politwitter.ca'; else $pre = ''; 
$description = preg_replace("/(http:\/\/[^\s]+)/", "<a href=\"$1\" target=\"_blank\">$1</a>", $description); 
$description = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>'", $description); 
$description = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", "'\\1<a href=\"".$pre."/user/\\2\" rel=\"nofollow\">@\\2</a>'", $description); 
$description = preg_replace("#(^|[\n ])\#([^ \"\t\n\r<]*)#ise", "'\\1<a href=\"".$pre."/hash/\\2\" rel=\"nofollow\" class=\"hash ".$colour."\">#\\2</a>'", $description); 
return $description; 

}

回答

2

最簡單的代碼的修改做你想做什麼:

$description = preg_replace("#(^|[\n ])\#(\w+)#ise", "'\\1<a href=\"".$pre."/hash/\\2\" rel=\"nofollow\" class=\"hash ".$colour."\">#\\2</a>'", $description); 
+0

太感謝你了,那的偉大工程!我對上面的規則做了同樣的修改。 – Canadaka 2009-08-13 10:31:57