【问题标题】:Regex to conditionally replace Twitter hashtags with hyperlinks正则表达式有条件地用超链接替换 ​​Twitter 主题标签
【发布时间】:2011-05-15 16:37:45
【问题描述】:

我正在编写一个小的 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 获得的那个,它只会有条件地将主题标签重写为超链接,前提是它们不只包含数字?

【问题讨论】:

    标签: php regex twitter hashtag


    【解决方案1】:
    (^|\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

    【讨论】:

    • 啊,完美!而且也非常简单……我的大脑今天不太正常。 :p 非常感谢!
    • 这是否考虑到特殊字符,@Gazler ?说它会用#Prévoyance 之类的词吗?
    • @Jeremy 不,但这应该可以解决问题(^|\s)#(\w*[\S!#]+\w*)
    • "# #abc" 会匹配 "#abc" 而不是 "#abc"(注意空格)。
    【解决方案2】:

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

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

    preg_match('/([ ,.]+)/', $string, $matches);
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        (^|\s)
        

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

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

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

        【讨论】:

        • 你修改后的表达式不是和#(\w*\w+\w*)一样吗?
        • 无论哪种方式,Gazler 的答案都有效,它实际上并没有在主题标签的开头添加空格,而是捕获了两组,但您只需要第二组。
        猜你喜欢
        • 1970-01-01
        • 2017-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-12
        • 2017-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多