代码之家  ›  专栏  ›  技术社区  ›  foxsoup

Regex有条件地用超链接替换Twitter标签

  •  9
  • foxsoup  · 技术社区  · 15 年前

    我正在编写一个小的PHP脚本,从用户feed中获取最新的6个Twitter状态更新,并将其格式化以显示在网页上。作为这项工作的一部分,我需要一个regex替换来将标签重写为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”不是。经过在互联网上的一点检查和各种各样的标签,我得出结论,一个标签必须包含字母字符或下划线,在它的某处组成一个链接;只有数字字符的标签被忽略(大概是为了阻止像“好的演示鲍勃,幻灯片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_替换类似于我从gist.github获得的替换,它将有条件地将标签重写为超链接,只要它们不包含数字?

    4 回复  |  直到 15 年前
        1
  •  23
  •   rishabhmhjn Gazler    12 年前
    (^|\s)#(\w*[a-zA-Z_]+\w*)
    

    菲律宾比索

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

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

    http://rubular.com/r/opNX6qC4sG &在这里测试一下。

        2
  •  1
  •   Jack Read    15 年前

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

    以下对我很有用。。。

    preg_match('/([ ,.]+)/', $string, $matches);
    
        3
  •  0
  •   Alberto Zaccagni    15 年前

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

        4
  •  0
  •   Community Mohan Dere    9 年前

    我找到了观察家 answer 为了工作,尽管regex在标签的开头添加了一个空格,所以我删除了第一部分:

    (^|\s)
    

    这对我来说很好:

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

    示例如下: http://rubular.com/r/dS2QYZP45n

    推荐文章