9

我正在编写一个小的 PHP 脚本来从用户提要中获取最新的半打 Twitter 状态更新,并将它们格式化以显示在网页上。作为其中的一部分,我需要一个正则表达式替换来将主题标签重写为 search.twitter.com 的超链接。最初我尝试使用:

<?php
$strTweet = preg_replace('/(^|\s)#(\w+)/', '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', $strTweet);
?>

(取自https://gist.github.com/445729

在测试过程中,我发现#test 被转换为 Twitter 网站上的链接,但 #123 不是。在互联网上进行了一些检查并使用了各种标签后,我得出结论,主题标签必须在某处包含字母字符或下划线才能构成链接;仅包含数字字符的标签将被忽略(可能是为了阻止诸如“Bob 的演示文稿很好,幻灯片 #3 是我最喜欢的!”之类的东西被链接)。这使得上面的代码不正确,因为它很乐意将#123 转换为链接。

我有一段时间没有做太多正则表达式了,所以在我生疏的情况下,我想出了以下 PHP 解决方案:

<?php
$test = 'This is a test tweet to see if #123 and #4 are not encoded but #test, #l33t and #8oo8s are.';

// Get all hashtags out into an array
if (preg_match_all('/(^|\s)(#\w+)/', $test, $arrHashtags) > 0) {
  foreach ($arrHashtags[2] as $strHashtag) {
    // Check each tag to see if there are letters or an underscore in there somewhere
    if (preg_match('/#\d*[a-z_]+/i', $strHashtag)) {
      $test = str_replace($strHashtag, '<a href="http://search.twitter.com/search?q=%23'.substr($strHashtag, 1).'">'.$strHashtag.'</a>', $test);
    }
  }
}

echo $test;
?>

有用; 但它的作用似乎相当冗长。我的问题是,是否有一个 preg_replace 类似于我从 gist.github 获得的那个,只有当它们不包含数字时才会有条件地将主题标签重写为超链接?

4

4 回答 4

23
(^|\s)#(\w*[a-zA-Z_]+\w*)

PHP

$strTweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1#<a href="http://twitter.com/search?q=%23\2">\2</a>', $strTweet);

此正则表达式表示 # 后跟 0 个或多个字符 [a-zA-Z0-9_],后跟一个字母字符或下划线(1 个或多个),然后是 0 个或多个单词字符。

http://rubular.com/r/opNX6qC4sG <- 在这里测试。

于 2010-11-25T12:33:08.013 回答
1

实际上最好搜索主题标签中不允许的字符,否则像“#Trentemøller”这样的标签将不起作用。

以下对我很有效......

preg_match('/([ ,.]+)/', $string, $matches);
于 2011-05-30T20:06:23.760 回答
0

我设计了这个:/(^|\s)#([[:alnum:]])+/gi

于 2010-11-25T13:09:48.040 回答
0

我发现 Gazlers的回答可以工作,尽管正则表达式在主题标签的开头添加了一个空格,所以我删除了第一部分:

(^|\s)

现在这对我来说非常有效:

#(\w*[a-zA-Z_0-9]+\w*)

此处示例:http ://rubular.com/r/dS2QYZP45n

于 2013-09-11T22:26:55.383 回答