正则表达式有条件地用超链接替换Twitter主题标签

fox*_*oup 9 php regex twitter hashtag

我正在编写一个小的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);
?>
Run Code Online (Sandbox Code Playgroud)

(摘自https://gist.github.com/445729)

在测试过程中,我发现#test被转换为Twitter网站上的链接,但#123不是.在对互联网进行了一些检查并使用各种标签后,我得出的结论是,标签必须包含字母字符或其中的下划线以构成链接; 只有数字字符的标签会被忽略(大概是为了停止像"好的演示文稿鲍勃,幻灯片#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;
?>
Run Code Online (Sandbox Code Playgroud)

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

Gaz*_*ler 23

(^|\s)#(\w*[a-zA-Z_]+\w*)
Run Code Online (Sandbox Code Playgroud)

PHP

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

该正则表达式表示一#后跟0或多个字符[A-ZA-Z0-9_],接着字母字符或下划线(1或多个),其次是0或多个单词字符.

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