我需要一些帮助来改进我为解析Twitter中的链接所做的这个功能。它为hashtags和@replys创建链接。一切正常,问题是如果标签或@reply末尾有一个没有空格的标点符号,它会被添加到HREF URL。
例如,如果我发推文“我真的很喜欢#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;
}
答案 0 :(得分:2)
最简单地修改代码以执行您想要的操作:
$description = preg_replace("#(^|[\n ])\#(\w+)#ise", "'\\1<a href=\"".$pre."/hash/\\2\" rel=\"nofollow\" class=\"hash ".$colour."\">#\\2</a>'", $description);