2009-08-12 34 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